...

Package berkeley

import "goberkeley/berkeley"
Overview
Index

Overview ▾

Index ▾

type AbstractNode
    func InitializeNodeWithAddresses(name, address string, timeout time.Duration, addresses map[string]string) (*AbstractNode, error)
    func NewAbstractNode(name, address string, timeout time.Duration) (*AbstractNode, error)
    func (n *AbstractNode) Close() error
    func (n *AbstractNode) SendMessageAsync(address, message string) error
    func (n *AbstractNode) SendMessageSync(address string, message string) (string, error)
    func (n *AbstractNode) StartListening() error
type Config
    func LoadConfig(filepath string) *Config
type DeltaRequest
type ErrorType
type Follower
    func InitializeFollowerNode(name, address, leaderAddress string, timeout time.Duration) (*Follower, error)
    func NewFollower(name, address, leaderAddress string, timeout time.Duration) (*Follower, error)
    func (f *Follower) HandleProcess(message string) (string, error)
    func (f *Follower) StartAlgorithm() error
type FollowerConfig
type FollowerInfo
    func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo
    func (f *FollowerInfo) GetAddress() string
    func (f *FollowerInfo) GetCommunicationTime() int64
    func (f *FollowerInfo) GetDateFollower() time.Time
    func (f *FollowerInfo) GetDelta() int64
    func (f *FollowerInfo) GetDiffTime() int64
    func (f *FollowerInfo) GetLocalTime() int64
    func (f *FollowerInfo) GetName() string
    func (f *FollowerInfo) GetState() FollowerState
    func (f *FollowerInfo) SetDelta(delta int64)
    func (f *FollowerInfo) SetState(state FollowerState)
    func (f *FollowerInfo) String() string
type FollowerState
type Handler
type INode
type Leader
    func InitializeLeaderNode(name, address string, timeout time.Duration, nodeAddresses map[string]string) (*Leader, error)
    func (l *Leader) Close()
    func (l *Leader) HandleProcess(message string) (string, error)
    func (l *Leader) StartAlgorithm()
type LeaderConfig
type LoggerManager
    func (LoggerManager) GetLogger(clazz interface{}) *logrus.Logger
type SocketZeroMQException
    func NewSocketZeroMQException(message string, errorType ErrorType) *SocketZeroMQException
    func (e *SocketZeroMQException) Error() string
    func (e *SocketZeroMQException) GetErrorType() ErrorType
type TimeRequest

Package files

anode.go config.go follower.go follower_info.go follower_state.go inode.go leader.go logger_manager.go socket_zero_mq_exception.go

type AbstractNode

AbstractNode proporciona la funcionalidad base para nodos en el sistema.

type AbstractNode struct {
    Name          string
    Address       string
    Timeout       time.Duration
    NodeAddresses map[string]string
    Context       *zmq.Context
    Socket        *zmq.Socket
    Logger        *log.Logger
    Handler       // Composición de la interfaz Handler
}

func InitializeNodeWithAddresses

func InitializeNodeWithAddresses(name, address string, timeout time.Duration, addresses map[string]string) (*AbstractNode, error)

InitializeNodeWithAddresses inicializa un nodo con direcciones de otros nodos.

func NewAbstractNode

func NewAbstractNode(name, address string, timeout time.Duration) (*AbstractNode, error)

NewAbstractNode crea e inicializa un nuevo nodo base.

func (*AbstractNode) Close

func (n *AbstractNode) Close() error

Close cierra los recursos del nodo.

func (*AbstractNode) SendMessageAsync

func (n *AbstractNode) SendMessageAsync(address, message string) error

SendMessageAsync envía un mensaje de manera asíncrona.

func (*AbstractNode) SendMessageSync

func (n *AbstractNode) SendMessageSync(address string, message string) (string, error)

SendMessageSync envía un mensaje de forma síncrona y espera una respuesta.

func (*AbstractNode) StartListening

func (n *AbstractNode) StartListening() error

StartListening inicia el proceso de escucha para mensajes entrantes en el nodo. Configura un socket de tipo REP (Response) para recibir y responder a mensajes.

type Config

type Config struct {
    Leader    LeaderConfig     `json:"leader"`
    Followers []FollowerConfig `json:"followers"`
    Timeout   time.Duration    `json:"timeout"`
}

func LoadConfig

func LoadConfig(filepath string) *Config

type DeltaRequest

type DeltaRequest struct {
    Message    string `json:"message"`
    Operation  string `json:"operation"`
    Delta      int64  `json:"delta"`
    LeaderAddr string `json:"leader_address"`
}

type ErrorType

ErrorType enum para los diferentes tipos de errores posibles en ZeroMQ.

type ErrorType int
const (
    // CONNECTION_ERROR Error relacionado con la conexión de ZeroMQ
    CONNECTION_ERROR ErrorType = iota
    // SEND_ERROR Error al enviar un mensaje a través del socket
    SEND_ERROR
    // RECEIVE_ERROR Error al recibir un mensaje del socket
    RECEIVE_ERROR
)

type Follower

Follower representa un nodo seguidor en el sistema distribuido.

type Follower struct {
    LeaderAddress string
    // contains filtered or unexported fields
}

func InitializeFollowerNode

func InitializeFollowerNode(name, address, leaderAddress string, timeout time.Duration) (*Follower, error)

InitializeNode inicializa el nodo seguidor con su información específica.

func NewFollower

func NewFollower(name, address, leaderAddress string, timeout time.Duration) (*Follower, error)

NewFollower crea e inicializa un nuevo nodo seguidor.

func (*Follower) HandleProcess

func (f *Follower) HandleProcess(message string) (string, error)

HandleProcess maneja y procesa los mensajes recibidos del líder. Implementación de HandleProcess para Follower

func (*Follower) StartAlgorithm

func (f *Follower) StartAlgorithm() error

StartAlgorithm configura e inicia el socket REP para escuchar mensajes entrantes y delega la responsabilidad de iniciar la escucha al nodo abstracto. StartAlgorithm configura e inicia la escucha en el seguidor

type FollowerConfig

type FollowerConfig struct {
    Name    string `json:"name"`
    Address string `json:"address"`
}

type FollowerInfo

FollowerInfo encapsula información sobre un nodo seguidor en el sistema.

type FollowerInfo struct {
    Name              string        // Nombre del seguidor
    Address           string        // Dirección del seguidor en formato "host:puerto"
    State             FollowerState // Estado actual del seguidor
    DateFollower      time.Time     // Fecha y hora local del seguidor
    LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
    CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
    TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
    DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
    Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
}

func NewFollowerInfo

func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo

NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.

func (*FollowerInfo) GetAddress

func (f *FollowerInfo) GetAddress() string

GetAddress devuelve la dirección del seguidor.

func (*FollowerInfo) GetCommunicationTime

func (f *FollowerInfo) GetCommunicationTime() int64

GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.

func (*FollowerInfo) GetDateFollower

func (f *FollowerInfo) GetDateFollower() time.Time

GetDateFollower devuelve la fecha y hora local del seguidor.

func (*FollowerInfo) GetDelta

func (f *FollowerInfo) GetDelta() int64

GetDelta devuelve la diferencia global de tiempo (delta).

func (*FollowerInfo) GetDiffTime

func (f *FollowerInfo) GetDiffTime() int64

GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.

func (*FollowerInfo) GetLocalTime

func (f *FollowerInfo) GetLocalTime() int64

GetLocalTime devuelve la hora local del seguidor.

func (*FollowerInfo) GetName

func (f *FollowerInfo) GetName() string

GetName devuelve el nombre del seguidor.

func (*FollowerInfo) GetState

func (f *FollowerInfo) GetState() FollowerState

GetState devuelve el estado actual del seguidor.

func (*FollowerInfo) SetDelta

func (f *FollowerInfo) SetDelta(delta int64)

SetDelta establece la diferencia global de tiempo (delta) para el seguidor.

func (*FollowerInfo) SetState

func (f *FollowerInfo) SetState(state FollowerState)

SetState establece el estado del seguidor.

func (*FollowerInfo) String

func (f *FollowerInfo) String() string

String genera una representación en cadena del objeto FollowerInfo.

type FollowerState

FollowerState representa los posibles estados de un seguidor durante el proceso de actualización de la hora del sistema.

type FollowerState string
const (
    // RESPONDED indica que el seguidor ha respondido correctamente a la solicitud del líder.
    Responded FollowerState = "RESPONDED"

    // NO_RESPONSE indica que el seguidor no ha respondido a la solicitud dentro del tiempo esperado.
    NoResponse FollowerState = "NO_RESPONSE"

    // CONNECTION_ERROR indica que hubo un error de conexión al intentar comunicarse con el seguidor.
    ConnectionError FollowerState = "CONNECTION_ERROR"

    // REQUEST_NOT_SENT indica que la solicitud de actualización de la hora no fue enviada debido a algún error.
    RequestNotSent FollowerState = "REQUEST_NOT_SENT"

    // REQUEST_DELTA_SENT indica que la solicitud de actualización de la hora fue enviada al seguidor para actualizar su hora.
    RequestDeltaSent FollowerState = "REQUEST_DELTA_SENT"

    // TIME_ERROR_SENT_UPDATE indica que la solicitud de actualización de la hora fue enviada pero hubo un error en ese envío.
    TimeErrorSentUpdate FollowerState = "TIME_ERROR_SENT_UPDATE"

    // TIME_UPDATED indica que la hora del sistema del seguidor se actualizó correctamente.
    TimeUpdated FollowerState = "TIME_UPDATED"

    // ERROR_CLOSE indica que  no pude enviar el cierre del socket en el seguidor.
    ErrorClose FollowerState = "ERROR_CLOSE"

    // Ok_CLOSE indica que   pude  cerrar el socket en el seguidor.
    OkClose FollowerState = "Ok_CLOSE"
)

type Handler

Interfaz Handler con el método HandleProcess

type Handler interface {
    HandleProcess(message string) (string, error)
}

type INode

INode define las operaciones básicas para un nodo en el sistema.

type INode interface {
    InitializeNode(name string, address string, timeout time.Duration) error
    InitializeNodeWithAddresses(name string, address string, timeout time.Duration, addresses map[string]string) error
    SendMessageSync(address string, message string) (string, error)
    SendMessageAsync(address string, message string) error
    StartListening() error
    StartAlgorithm() error
    Close() error
}

type Leader

Leader representa el nodo líder en el sistema Berkeley.

type Leader struct {
    UnreachableFollowers   map[string]*FollowerInfo
    SuccessfulFollowers    map[string]*FollowerInfo
    NonRespondingFollowers map[string]*FollowerInfo
    TimeUpdatedFollowers   map[string]*FollowerInfo
    FailedFollowers        map[string]*FollowerInfo
    //mu                     sync.Mutex // Mutex para proteger los mapas en accesos concurrentes
    Logger *log.Logger
    // contains filtered or unexported fields
}

func InitializeLeaderNode

func InitializeLeaderNode(name, address string, timeout time.Duration, nodeAddresses map[string]string) (*Leader, error)

InitializeLeaderNode crea e inicializa un nuevo nodo líder.

func (*Leader) Close

func (l *Leader) Close()

func (*Leader) HandleProcess

func (l *Leader) HandleProcess(message string) (string, error)

HandleProcess implements Handler.

func (*Leader) StartAlgorithm

func (l *Leader) StartAlgorithm()

StartAlgorithm implementa el algoritmo de sincronización Berkeley para el líder.

type LeaderConfig

type LeaderConfig struct {
    Name    string `json:"name"`
    Address string `json:"address"`
}

type LoggerManager

LoggerManager es responsable de gestionar los loggers para las clases que lo invocan.

type LoggerManager struct{}

func (LoggerManager) GetLogger

func (LoggerManager) GetLogger(clazz interface{}) *logrus.Logger

GetLogger obtiene el logger correspondiente a la clase que invoca este método.

type SocketZeroMQException

SocketZeroMQException estructura que encapsula un error personalizado para ZeroMQ.

type SocketZeroMQException struct {
    Message   string    // Mensaje de error
    ErrorType ErrorType // Tipo de error
}

func NewSocketZeroMQException

func NewSocketZeroMQException(message string, errorType ErrorType) *SocketZeroMQException

NewSocketZeroMQException crea una nueva instancia de SocketZeroMQException.

func (*SocketZeroMQException) Error

func (e *SocketZeroMQException) Error() string

Error implementación de la interfaz error para SocketZeroMQException.

func (*SocketZeroMQException) GetErrorType

func (e *SocketZeroMQException) GetErrorType() ErrorType

GetErrorType obtiene el tipo de error.

type TimeRequest

Mensaje JSON que se envía al seguidor.

type TimeRequest struct {
    Message    string `json:"message"`
    Operation  string `json:"operation"`
    Time       int64  `json:"time"`
    LeaderAddr string `json:"leader_address"`
}
body { margin: 0; font-family: Arial, sans-serif; background-color: #fff; line-height: 1.3; text-align: center; color: #222; } textarea { /* Inherit text color from body avoiding illegible text in the case where the * user has inverted the browsers custom text and background colors. */ color: inherit; } pre, code { font-family: Menlo, monospace; font-size: 0.875rem; } pre { line-height: 1.4; overflow-x: auto; } pre .comment { color: #006600; } pre .highlight, pre .highlight-comment, pre .selection-highlight, pre .selection-highlight-comment { background: #ffff00; } pre .selection, pre .selection-comment { background: #ff9632; } pre .ln { color: #999; background: #efefef; } .ln { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; /* Ensure 8 characters in the document - which due to floating * point rendering issues, might have a width of less than 1 each - are 8 * characters wide, so a tab in the 9th position indents properly. See * https://github.com/webcompat/web-bugs/issues/17530#issuecomment-402675091 * for more information. */ display: inline-block; width: 8ch; } .search-nav { margin-left: 1.25rem; font-size: 0.875rem; column-gap: 1.25rem; column-fill: auto; column-width: 14rem; } .search-nav .indent { margin-left: 1.25rem; } a, .exampleHeading .text, .expandAll { color: #375eab; text-decoration: none; } a:hover, .exampleHeading .text:hover, .expandAll:hover { text-decoration: underline; } .article a { text-decoration: underline; } .article .title a { text-decoration: none; } .permalink { display: none; } :hover > .permalink { display: inline; } p, li { max-width: 50rem; word-wrap: break-word; } p, pre, ul, ol { margin: 1.25rem; } pre { background: #efefef; padding: 0.625rem; border-radius: 0.3125rem; } h1, h2, h3, h4, .rootHeading { margin: 1.25rem 0 1.25rem; padding: 0; color: #375eab; font-weight: bold; } h1 { font-size: 1.75rem; line-height: 1; } h1 .text-muted { color: #777; } h2 { font-size: 1.25rem; background: #e0ebf5; padding: 0.5rem; line-height: 1.25; font-weight: normal; overflow: auto; overflow-wrap: break-word; } h2 a { font-weight: bold; } h3 { font-size: 1.25rem; line-height: 1.25; overflow: auto; overflow-wrap: break-word; } h3, h4 { margin: 1.25rem 0.3125rem; } h4 { font-size: 1rem; } .rootHeading { font-size: 1.25rem; margin: 0; } h2 > span, h3 > span { float: right; margin: 0 25px 0 0; font-weight: normal; color: #5279c7; } dl { margin: 1.25rem; } dd { margin: 0 0 0 1.25rem; } dl, dd { font-size: 0.875rem; } div#nav table td { vertical-align: top; } #pkg-index h3 { font-size: 1rem; } .pkg-dir { padding: 0 0.625rem; } .pkg-dir table { border-collapse: collapse; border-spacing: 0; } .pkg-name { padding-right: 0.625rem; } .alert { color: #aa0000; } .top-heading { float: left; padding: 1.313rem 0; font-size: 1.25rem; font-weight: normal; } .top-heading a { color: #222; text-decoration: none; } #pkg-examples h3 { float: left; } #pkg-examples dl { clear: both; } .expandAll { cursor: pointer; float: left; margin: 1.25rem 0; } div#topbar { background: #e0ebf5; height: 4rem; overflow: hidden; } div#page { width: 100%; } div#page > .container, div#topbar > .container { text-align: left; margin-left: auto; margin-right: auto; padding: 0 1.25rem; } div#topbar > .container, div#page > .container { max-width: 59.38rem; } div#page.wide > .container, div#topbar.wide > .container { max-width: none; } div#plusone { float: right; clear: right; margin-top: 0.3125rem; } div#footer { text-align: center; color: #666; font-size: 0.875rem; margin: 2.5rem 0; } div#menu > a, input#search, div#learn .buttons a, div.play .buttons a, div#blog .read a, #menu-button { padding: 0.625rem; text-decoration: none; font-size: 1rem; border-radius: 0.3125rem; } div#playground .buttons a, div#menu > a, input#search, #menu-button { border: 0.0625rem solid #375eab; } div#playground .buttons a, div#menu > a, #menu-button { color: white; background: #375eab; } #playgroundButton.active { background: white; color: #375eab; } a#start, div#learn .buttons a, div.play .buttons a, div#blog .read a { color: #222; border: 0.0625rem solid #375eab; background: #e0ebf5; } .download { width: 9.375rem; } div#menu { text-align: right; padding: 0.625rem; white-space: nowrap; max-height: 0; -moz-transition: max-height 0.25s linear; transition: max-height 0.25s linear; width: 100%; } div#menu.menu-visible { max-height: 31.25rem; } div#menu > a, #menu-button { margin: 0.625rem 0.125rem; padding: 0.625rem; } ::-webkit-input-placeholder { color: #7f7f7f; opacity: 1; } ::placeholder { color: #7f7f7f; opacity: 1; } #menu .search-box { display: inline-flex; width: 8.75rem; } input#search { background: white; color: #222; box-sizing: border-box; -webkit-appearance: none; border-top-right-radius: 0; border-bottom-right-radius: 0; border-right: 0; margin-right: 0; flex-grow: 1; max-width: 100%; min-width: 5.625rem; } input#search:-webkit-search-decoration { -webkit-appearance: none; } input#search:-moz-ui-invalid { box-shadow: unset; } input#search + button { display: inline; font-size: 1em; background-color: #375eab; color: white; border: 0.0625rem solid #375eab; border-top-left-radius: 0; border-top-right-radius: 0.3125rem; border-bottom-left-radius: 0; border-bottom-right-radius: 0.3125rem; margin-left: 0; cursor: pointer; } input#search + button span { display: flex; } input#search + button svg { fill: white; } #menu-button { display: none; position: absolute; right: 0.3125rem; top: 0; margin-right: 0.3125rem; } #menu-button-arrow { display: inline-block; } .vertical-flip { transform: rotate(-180deg); } div.left { float: left; clear: left; margin-right: 2.5%; } div.right { float: right; clear: right; margin-left: 2.5%; } div.left, div.right { width: 45%; } div#learn, div#about { padding-top: 1.25rem; } div#learn h2, div#about { margin: 0; } div#about { font-size: 1.25rem; margin: 0 auto 1.875rem; } a#start { display: block; padding: 0.625rem; text-align: center; text-decoration: none; border-radius: 0.3125rem; } a#start .big { display: block; font-weight: bold; font-size: 1.25rem; } a#start .desc { display: block; font-size: 0.875rem; font-weight: normal; margin-top: 0.3125rem; } div#learn .popout { float: right; display: block; cursor: pointer; font-size: 0.75rem; background: url(/doc/share.png) no-repeat; background-position: right center; padding: 0.375rem 1.688rem; } div#learn pre, div#learn textarea { padding: 0; margin: 0; font-family: Menlo, monospace; font-size: 0.875rem; } div#learn .input { padding: 0.625rem; margin-top: 0.625rem; height: 9.375rem; border-top-left-radius: 0.3125rem; border-top-right-radius: 0.3125rem; } div#learn .input textarea { width: 100%; height: 100%; border: none; outline: none; resize: none; } div#learn .output { border-top: none !important; padding: 0.625rem; height: 3.688rem; overflow: auto; border-bottom-right-radius: 0.3125rem; border-bottom-left-radius: 0.3125rem; } div#learn .output pre { padding: 0; border-radius: 0; } div#learn .input, div#learn .input textarea, div#learn .output, div#learn .output pre { background: #ffffd8; } div#learn .input, div#learn .output { border: 0.0625rem solid #375eab; } div#learn .buttons { float: right; padding: 1.25rem 0 0.625rem 0; text-align: right; } div#learn .buttons a { height: 1rem; margin-left: 0.3125rem; padding: 0.625rem; } div#learn .toys { margin-top: 0.5rem; } div#learn .toys select { font-size: 0.875rem; border: 0.0625rem solid #375eab; margin: 0; } div#learn .output .exit { display: none; } div#video { max-width: 100%; } div#blog, div#video { margin-top: 2.5rem; } div#blog > a, div#blog > div, div#blog > h2, div#video > a, div#video > div, div#video > h2 { margin-bottom: 0.625rem; } div#blog .title, div#video .title { display: block; font-size: 1.25rem; } div#blog .when { color: #666; font-size: 0.875rem; } div#blog .read { text-align: right; } @supports (--c: 0) { [style*='--aspect-ratio-padding:'] { position: relative; overflow: hidden; padding-top: var(--aspect-ratio-padding); } [style*='--aspect-ratio-padding:'] > * { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } } .toggleButton { cursor: pointer; } .toggle > .collapsed { display: block; } .toggle > .expanded { display: none; } .toggleVisible > .collapsed { display: none; } .toggleVisible > .expanded { display: block; } table.codetable { margin-left: auto; margin-right: auto; border-style: none; } table.codetable td { padding-right: 0.625rem; } hr { border-style: none; border-top: 0.0625rem solid black; } img.gopher { float: right; margin-left: 0.625rem; margin-top: -2.5rem; margin-bottom: 0.625rem; z-index: -1; } h2 { clear: right; } /* example and drop-down playground */ div.play { padding: 0 1.25rem 2.5rem 1.25rem; } div.play pre, div.play textarea, div.play .lines { padding: 0; margin: 0; font-family: Menlo, monospace; font-size: 0.875rem; } div.play .input { padding: 0.625rem; margin-top: 0.625rem; border-top-left-radius: 0.3125rem; border-top-right-radius: 0.3125rem; overflow: hidden; } div.play .input textarea { width: 100%; height: 100%; border: none; outline: none; resize: none; overflow: hidden; } div#playground .input textarea { overflow: auto; resize: auto; } div.play .output { border-top: none !important; padding: 0.625rem; max-height: 12.5rem; overflow: auto; border-bottom-right-radius: 0.3125rem; border-bottom-left-radius: 0.3125rem; } div.play .output pre { padding: 0; border-radius: 0; } div.play .input, div.play .input textarea, div.play .output, div.play .output pre { background: #ffffd8; } div.play .input, div.play .output { border: 0.0625rem solid #375eab; } div.play .buttons { float: right; padding: 1.25rem 0 0.625rem 0; text-align: right; } div.play .buttons a { height: 1rem; margin-left: 0.3125rem; padding: 0.625rem; cursor: pointer; } .output .stderr { color: #933; } .output .system { color: #999; } /* drop-down playground */ div#playground { /* start hidden; revealed by javascript */ display: none; } div#playground { position: absolute; top: 3.938rem; right: 1.25rem; padding: 0 0.625rem 0.625rem 0.625rem; z-index: 1; text-align: left; background: #e0ebf5; border: 0.0625rem solid #b0bbc5; border-top: none; border-bottom-left-radius: 0.3125rem; border-bottom-right-radius: 0.3125rem; } div#playground .code { width: 32.5rem; height: 12.5rem; } div#playground .output { height: 6.25rem; } /* Inline runnable snippets (play.js/initPlayground) */ #content .code pre, #content .playground pre, #content .output pre { margin: 0; padding: 0; background: none; border: none; outline: 0 solid transparent; overflow: auto; } #content .playground .number, #content .code .number { color: #999; } #content .code, #content .playground, #content .output { width: auto; margin: 1.25rem; padding: 0.625rem; border-radius: 0.3125rem; } #content .code, #content .playground { background: #e9e9e9; } #content .output { background: #202020; } #content .output .stdout, #content .output pre { color: #e6e6e6; } #content .output .stderr, #content .output .error { color: rgb(244, 74, 63); } #content .output .system, #content .output .exit { color: rgb(255, 209, 77); } #content .buttons { position: relative; float: right; top: -3.125rem; right: 1.875rem; } #content .output .buttons { top: -3.75rem; right: 0; height: 0; } #content .buttons .kill { display: none; visibility: hidden; } a.error { font-weight: bold; color: white; background-color: darkred; border-bottom-left-radius: 0.25rem; border-bottom-right-radius: 0.25rem; border-top-left-radius: 0.25rem; border-top-right-radius: 0.25rem; padding: 0.125rem 0.25rem 0.125rem 0.25rem; /* TRBL */ } #heading-narrow { display: none; } .downloading { background: #f9f9be; padding: 0.625rem; text-align: center; border-radius: 0.3125rem; } @media (max-width: 58.125em) { #heading-wide { display: none; } #heading-narrow { display: block; } } @media (max-width: 47.5em) { .container .left, .container .right { width: auto; float: none; } div#about { max-width: 31.25rem; text-align: center; } } @media (min-width: 43.75em) and (max-width: 62.5em) { div#menu > a { margin: 0.3125rem 0; font-size: 0.875rem; } input#search { font-size: 0.875rem; } } @media (max-width: 43.75em) { body { font-size: 0.9375rem; } div#playground { left: 0; right: 0; } pre, code { font-size: 0.866rem; } div#page > .container { padding: 0 0.625rem; } div#topbar { height: auto; padding: 0.625rem; } div#topbar > .container { padding: 0; } #heading-wide { display: block; } #heading-narrow { display: none; } .top-heading { float: none; display: inline-block; padding: 0.75rem; } div#menu { padding: 0; min-width: 0; text-align: left; float: left; } div#menu > a { display: block; margin-left: 0; margin-right: 0; } #menu .search-box { display: flex; width: 100%; } #menu-button { display: inline-block; } p, pre, ul, ol { margin: 0.625rem; } .pkg-synopsis { display: none; } img.gopher { display: none; } } @media (max-width: 30em) { #heading-wide { display: none; } #heading-narrow { display: block; } } @media print { pre { background: #fff; border: 0.0625rem solid #bbb; white-space: pre-wrap; } } /*! jQuery v3.6.1 | (c) OpenJS Foundation and other contributors | jquery.org/license */ !function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(e.document)return t(e);throw new Error("jQuery requires a window with a document")}:t(e)}("undefined"!=typeof window?window:this,function(w,R){"use strict";function v(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item}function g(e){return null!=e&&e===e.window}var t=[],M=Object.getPrototypeOf,s=t.slice,I=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},W=t.push,F=t.indexOf,$={},B=$.toString,_=$.hasOwnProperty,z=_.toString,U=z.call(Object),y={},T=w.document,X={type:!0,src:!0,nonce:!0,noModule:!0};function V(e,t,n){var r,i,o=(n=n||T).createElement("script");if(o.text=e,t)for(r in X)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function h(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?$[B.call(e)]||"object":typeof e}var e="3.6.1",C=function(e,t){return new C.fn.init(e,t)};function G(e){var t=!!e&&"length"in e&&e.length,n=h(e);return!v(e)&&!g(e)&&("array"===n||0===t||"number"==typeof t&&0>10|55296,1023&e|56320))}function M(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e}function I(){T()}var e,p,b,o,W,d,F,$,w,u,l,T,C,n,E,h,r,i,g,S="sizzle"+ +new Date,f=R.document,k=0,B=0,_=q(),z=q(),U=q(),y=q(),X=function(e,t){return e===t&&(l=!0),0},V={}.hasOwnProperty,t=[],G=t.pop,Y=t.push,A=t.push,Q=t.slice,v=function(e,t){for(var n=0,r=e.length;n+~]|"+a+")"+a+"*"),re=new RegExp(a+"|>"),ie=new RegExp(Z),oe=new RegExp("^"+s+"$"),x={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),TAG:new RegExp("^("+s+"|[*])"),ATTR:new RegExp("^"+K),PSEUDO:new RegExp("^"+Z),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+a+"*(even|odd|(([+-]|)(\\d*)n|)"+a+"*(?:([+-]|)"+a+"*(\\d+)|))"+a+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+a+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+a+"*((?:-\\d)?\\d*)"+a+"*\\)|)(?=[^-]|$)","i")},ae=/HTML$/i,se=/^(?:input|select|textarea|button)$/i,ue=/^h\d$/i,N=/^[^{]+\{\s*\[native \w/,le=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ce=/[+~]/,j=new RegExp("\\\\[\\da-fA-F]{1,6}"+a+"?|\\\\([^\\r\\n\\f])","g"),fe=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,pe=ve(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{A.apply(t=Q.call(f.childNodes),f.childNodes),t[f.childNodes.length].nodeType}catch(e){A={apply:t.length?function(e,t){Y.apply(e,Q.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function D(t,e,n,r){var i,o,a,s,u,l,c=e&&e.ownerDocument,f=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==f&&9!==f&&11!==f)return n;if(!r&&(T(e),e=e||C,E)){if(11!==f&&(s=le.exec(t)))if(i=s[1]){if(9===f){if(!(l=e.getElementById(i)))return n;if(l.id===i)return n.push(l),n}else if(c&&(l=c.getElementById(i))&&g(e,l)&&l.id===i)return n.push(l),n}else{if(s[2])return A.apply(n,e.getElementsByTagName(t)),n;if((i=s[3])&&p.getElementsByClassName&&e.getElementsByClassName)return A.apply(n,e.getElementsByClassName(i)),n}if(p.qsa&&!y[t+" "]&&(!h||!h.test(t))&&(1!==f||"object"!==e.nodeName.toLowerCase())){if(l=t,c=e,1===f&&(re.test(t)||ne.test(t))){(c=ce.test(t)&&ye(e.parentNode)||e)===e&&p.scope||((a=e.getAttribute("id"))?a=a.replace(fe,M):e.setAttribute("id",a=S)),o=(u=d(t)).length;while(o--)u[o]=(a?"#"+a:":scope")+" "+P(u[o]);l=u.join(",")}try{return A.apply(n,c.querySelectorAll(l)),n}catch(e){y(t,!0)}finally{a===S&&e.removeAttribute("id")}}}return $(t.replace(m,"$1"),e,n,r)}function q(){var n=[];function r(e,t){return n.push(e+" ")>b.cacheLength&&delete r[n.shift()],r[e+" "]=t}return r}function L(e){return e[S]=!0,e}function H(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t)}}function de(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function he(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&pe(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function O(a){return L(function(o){return o=+o,L(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in p=D.support={},W=D.isXML=function(e){var t=e&&e.namespaceURI,e=e&&(e.ownerDocument||e).documentElement;return!ae.test(t||e&&e.nodeName||"HTML")},T=D.setDocument=function(e){var e=e?e.ownerDocument||e:f;return e!=C&&9===e.nodeType&&e.documentElement&&(n=(C=e).documentElement,E=!W(C),f!=C&&(e=C.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",I,!1):e.attachEvent&&e.attachEvent("onunload",I)),p.scope=H(function(e){return n.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),p.attributes=H(function(e){return e.className="i",!e.getAttribute("className")}),p.getElementsByTagName=H(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),p.getElementsByClassName=N.test(C.getElementsByClassName),p.getById=H(function(e){return n.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),p.getById?(b.filter.ID=function(e){var t=e.replace(j,c);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E)return(t=t.getElementById(e))?[t]:[]}):(b.filter.ID=function(e){var t=e.replace(j,c);return function(e){e="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return e&&e.value===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=p.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):p.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"!==e)return o;while(n=o[i++])1===n.nodeType&&r.push(n);return r},b.find.CLASS=p.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},r=[],h=[],(p.qsa=N.test(C.querySelectorAll))&&(H(function(e){var t;n.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&h.push("[*^$]="+a+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||h.push("\\["+a+"*(?:value|"+J+")"),e.querySelectorAll("[id~="+S+"-]").length||h.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||h.push("\\["+a+"*name"+a+"*="+a+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||h.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||h.push(".#.+[+~]"),e.querySelectorAll("\\\f"),h.push("[\\r\\n\\f]")}),H(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&h.push("name"+a+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&h.push(":enabled",":disabled"),n.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(p.matchesSelector=N.test(i=n.matches||n.webkitMatchesSelector||n.mozMatchesSelector||n.oMatchesSelector||n.msMatchesSelector))&&H(function(e){p.disconnectedMatch=i.call(e,"*"),i.call(e,"[s!='']:x"),r.push("!=",Z)}),h=h.length&&new RegExp(h.join("|")),r=r.length&&new RegExp(r.join("|")),e=N.test(n.compareDocumentPosition),g=e||N.test(n.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,t=t&&t.parentNode;return e===t||!(!t||1!==t.nodeType||!(n.contains?n.contains(t):e.compareDocumentPosition&&16&e.compareDocumentPosition(t)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},X=e?function(e,t){var n;return e===t?(l=!0,0):(n=!e.compareDocumentPosition-!t.compareDocumentPosition)||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!p.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==f&&g(f,e)?-1:t==C||t.ownerDocument==f&&g(f,t)?1:u?v(u,e)-v(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?v(u,e)-v(u,t):0;if(i===o)return he(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?he(a[r],s[r]):a[r]==f?-1:s[r]==f?1:0}),C},D.matches=function(e,t){return D(e,null,null,t)},D.matchesSelector=function(e,t){if(T(e),p.matchesSelector&&E&&!y[t+" "]&&(!r||!r.test(t))&&(!h||!h.test(t)))try{var n=i.call(e,t);if(n||p.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){y(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(j,c),e[3]=(e[3]||e[4]||e[5]||"").replace(j,c),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||D.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&D.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return x.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&ie.test(n)&&(t=d(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(j,c).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=_[e+" "];return t||(t=new RegExp("(^|"+a+")"+e+"("+a+"|$)"))&&_(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(t,n,r){return function(e){e=D.attr(e,t);return null==e?"!="===n:!n||(e+="","="===n?e===r:"!="===n?e!==r:"^="===n?r&&0===e.indexOf(r):"*="===n?r&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function K(e,n,r){return v(n)?C.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?C.grep(e,function(e){return e===n!==r}):"string"!=typeof n?C.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/,te=((C.fn.init=function(e,t,n){if(e){if(n=n||Z,"string"!=typeof e)return e.nodeType?(this[0]=e,this.length=1,this):v(e)?void 0!==n.ready?n.ready(e):e(C):C.makeArray(e,this);if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:ee.exec(e))||!r[1]&&t)return(!t||t.jquery?t||n:this.constructor(t)).find(e);if(r[1]){if(t=t instanceof C?t[0]:t,C.merge(this,C.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:T,!0)),J.test(r[1])&&C.isPlainObject(t))for(var r in t)v(this[r])?this[r](t[r]):this.attr(r,t[r])}else(n=T.getElementById(r[2]))&&(this[0]=n,this.length=1)}return this}).prototype=C.fn,Z=C(T),/^(?:parents|prev(?:Until|All))/),ne={children:!0,contents:!0,next:!0,prev:!0};function re(e,t){while((e=e[t])&&1!==e.nodeType);return e}C.fn.extend({has:function(e){var t=C(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,Ce=/^$|^module$|\/(?:java|ecma)script/i,N=(L=T.createDocumentFragment().appendChild(T.createElement("div")),(o=T.createElement("input")).setAttribute("type","radio"),o.setAttribute("checked","checked"),o.setAttribute("name","t"),L.appendChild(o),y.checkClone=L.cloneNode(!0).cloneNode(!0).lastChild.checked,L.innerHTML="",y.noCloneChecked=!!L.cloneNode(!0).lastChild.defaultValue,L.innerHTML="",y.option=!!L.lastChild,{thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]});function j(e,t){var n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[];return void 0===t||t&&u(e,t)?C.merge([e],n):n}function Ee(e,t){for(var n=0,r=e.length;n",""]);var Se=/<|&#?\w+;/;function ke(e,t,n,r,i){for(var o,a,s,u,l,c=t.createDocumentFragment(),f=[],p=0,d=e.length;p\s*$/g;function Oe(e,t){return u(e,"table")&&u(11!==t.nodeType?t:t.firstChild,"tr")&&C(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Me(e,t){var n,r,i,o;if(1===t.nodeType){if(b.hasData(e)&&(o=b.get(e).events))for(i in b.remove(t,"handle events"),o)for(n=0,r=o[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),T.head.appendChild(r[0])},abort:function(){i&&i()}}}),[]),Qt=/(=)\?(?=&|$)|\?\?/,Jt=(C.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Yt.pop()||C.expando+"_"+Nt.guid++;return this[e]=!0,e}}),C.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Qt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Qt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=v(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Qt,"$1"+r):!1!==e.jsonp&&(e.url+=(jt.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||C.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=w[r],w[r]=function(){o=arguments},n.always(function(){void 0===i?C(w).removeProp(r):w[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Yt.push(r)),o&&v(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((o=T.implementation.createHTMLDocument("").body).innerHTML="
",2===o.childNodes.length),C.parseHTML=function(e,t,n){var r;return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=T.implementation.createHTMLDocument("")).createElement("base")).href=T.location.href,t.head.appendChild(r)):t=T),r=!n&&[],(n=J.exec(e))?[t.createElement(n[1])]:(n=ke([e],t,r),r&&r.length&&C(r).remove(),C.merge([],n.childNodes)))},C.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(C.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},C.expr.pseudos.animated=function(t){return C.grep(C.timers,function(e){return t===e.elem}).length},C.offset={setOffset:function(e,t,n){var r,i,o,a,s=C.css(e,"position"),u=C(e),l={};"static"===s&&(e.style.position="relative"),o=u.offset(),r=C.css(e,"top"),a=C.css(e,"left"),s=("absolute"===s||"fixed"===s)&&-1<(r+a).indexOf("auto")?(i=(s=u.position()).top,s.left):(i=parseFloat(r)||0,parseFloat(a)||0),null!=(t=v(t)?t.call(e,n,C.extend({},o)):t).top&&(l.top=t.top-o.top+i),null!=t.left&&(l.left=t.left-o.left+s),"using"in t?t.using.call(e,l):u.css(l)}},C.fn.extend({offset:function(t){var e,n;return arguments.length?void 0===t?this:this.each(function(e){C.offset.setOffset(this,t,e)}):(n=this[0])?n.getClientRects().length?(e=n.getBoundingClientRect(),n=n.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===C.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===C.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=C(e).offset()).top+=C.css(e,"borderTopWidth",!0),i.left+=C.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-C.css(r,"marginTop",!0),left:t.left-i.left-C.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===C.css(e,"position"))e=e.offsetParent;return e||S})}}),C.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;C.fn[t]=function(e){return f(this,function(e,t,n){var r;if(g(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),C.each(["top","left"],function(e,n){C.cssHooks[n]=tt(y.pixelPosition,function(e,t){if(t)return t=et(e,n),Ge.test(t)?C(e).position()[n]+"px":t})}),C.each({Height:"height",Width:"width"},function(a,s){C.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){C.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return f(this,function(e,t,n){var r;return g(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?C.css(e,t,i):C.style(e,t,n,i)},s,n?e:void 0,n)}})}),C.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){C.fn[t]=function(e){return this.on(t,e)}}),C.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),C.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){C.fn[n]=function(e,t){return 0 0) { return; } // For search, we send the toc precomputed from server-side. // TODO: Ideally, this should always be precomputed for all pages, but then // we need to do HTML parsing on the server-side. if (location.pathname === '/search') { return; } var nav = $('#nav'); if (nav.length === 0) { return; } var toc_items = []; $(nav) .nextAll('h2, h3') .each(function() { var node = this; if (node.id == '') node.id = 'tmp_' + toc_items.length; var link = $('') .attr('href', '#' + node.id) .text($(node).text()); var item; if ($(node).is('h2')) { item = $('
'); } else { // h3 item = $('
'); } item.append(link); toc_items.push(item); }); if (toc_items.length <= 1) { return; } var dl1 = $('
'); var dl2 = $('
'); var split_index = toc_items.length / 2 + 1; if (split_index < 8) { split_index = toc_items.length; } for (var i = 0; i < split_index; i++) { dl1.append(toc_items[i]); } for (; /* keep using i */ i < toc_items.length; i++) { dl2.append(toc_items[i]); } var tocTable = $('').appendTo(nav); var tocBody = $('').appendTo(tocTable); var tocRow = $('').appendTo(tocBody); // 1st column $('
') .appendTo(tocRow) .append(dl1); // 2nd column $('') .appendTo(tocRow) .append(dl2); } function bindToggle(el) { $('.toggleButton', el).click(function() { if ($(this).closest('.toggle, .toggleVisible')[0] != el) { // Only trigger the closest toggle header. return; } if ($(el).is('.toggle')) { $(el) .addClass('toggleVisible') .removeClass('toggle'); } else { $(el) .addClass('toggle') .removeClass('toggleVisible'); } }); } function bindToggles(selector) { $(selector).each(function(i, el) { bindToggle(el); }); } function bindToggleLink(el, prefix) { $(el).click(function() { var href = $(el).attr('href'); var i = href.indexOf('#' + prefix); if (i < 0) { return; } var id = '#' + prefix + href.slice(i + 1 + prefix.length); if ($(id).is('.toggle')) { $(id) .find('.toggleButton') .first() .click(); } }); } function bindToggleLinks(selector, prefix) { $(selector).each(function(i, el) { bindToggleLink(el, prefix); }); } function setupDropdownPlayground() { if (!$('#page').is('.wide')) { return; // don't show on front page } var button = $('#playgroundButton'); var div = $('#playground'); var setup = false; button.toggle( function() { button.addClass('active'); div.show(); if (setup) { return; } setup = true; playground({ codeEl: $('.code', div), outputEl: $('.output', div), runEl: $('.run', div), fmtEl: $('.fmt', div), shareEl: $('.share', div), shareRedirect: '//play.golang.org/p/', }); }, function() { button.removeClass('active'); div.hide(); } ); $('#menu').css('min-width', '+=60'); // Hide inline playground if we click somewhere on the page. // This is needed in mobile devices, where the "Play" button // is not clickable once the playground opens up. $('#page').click(function() { if (button.hasClass('active')) { button.click(); } }); } function setupInlinePlayground() { 'use strict'; // Set up playground when each element is toggled. $('div.play').each(function(i, el) { // Set up playground for this example. var setup = function() { var code = $('.code', el); playground({ codeEl: code, outputEl: $('.output', el), runEl: $('.run', el), fmtEl: $('.fmt', el), shareEl: $('.share', el), shareRedirect: '//play.golang.org/p/', }); // Make the code textarea resize to fit content. var resize = function() { code.height(0); var h = code[0].scrollHeight; code.height(h + 20); // minimize bouncing. code.closest('.input').height(h); }; code.on('keydown', resize); code.on('keyup', resize); code.keyup(); // resize now. }; // If example already visible, set up playground now. if ($(el).is(':visible')) { setup(); return; } // Otherwise, set up playground when example is expanded. var built = false; $(el) .closest('.toggle') .click(function() { // Only set up once. if (!built) { setup(); built = true; } }); }); } // fixFocus tries to put focus to div#page so that keyboard navigation works. function fixFocus() { var page = $('div#page'); var topbar = $('div#topbar'); page.css('outline', 0); // disable outline when focused page.attr('tabindex', -1); // and set tabindex so that it is focusable $(window) .resize(function(evt) { // only focus page when the topbar is at fixed position (that is, it's in // front of page, and keyboard event will go to the former by default.) // by focusing page, keyboard event will go to page so that up/down arrow, // space, etc. will work as expected. if (topbar.css('position') == 'fixed') page.focus(); }) .resize(); } function toggleHash() { var id = window.location.hash.substring(1); // Open all of the toggles for a particular hash. var els = $( document.getElementById(id), $('a[name]').filter(function() { return $(this).attr('name') == id; }) ); while (els.length) { for (var i = 0; i < els.length; i++) { var el = $(els[i]); if (el.is('.toggle')) { el.find('.toggleButton') .first() .click(); } } els = el.parent(); } } function personalizeInstallInstructions() { var prefix = '?download='; var s = window.location.search; if (s.indexOf(prefix) != 0) { // No 'download' query string; detect "test" instructions from User Agent. if (navigator.platform.indexOf('Win') != -1) { $('.testUnix').hide(); $('.testWindows').show(); } else { $('.testUnix').show(); $('.testWindows').hide(); } return; } var filename = s.substr(prefix.length); var filenameRE = /^go1\.\d+(\.\d+)?([a-z0-9]+)?\.([a-z0-9]+)(-[a-z0-9]+)?(-osx10\.[68])?\.([a-z.]+)$/; var m = filenameRE.exec(filename); if (!m) { // Can't interpret file name; bail. return; } $('.downloadFilename').text(filename); $('.hideFromDownload').hide(); var os = m[3]; var ext = m[6]; if (ext != 'tar.gz') { $('#tarballInstructions').hide(); } if (os != 'darwin' || ext != 'pkg') { $('#darwinPackageInstructions').hide(); } if (os != 'windows') { $('#windowsInstructions').hide(); $('.testUnix').show(); $('.testWindows').hide(); } else { if (ext != 'msi') { $('#windowsInstallerInstructions').hide(); } if (ext != 'zip') { $('#windowsZipInstructions').hide(); } $('.testUnix').hide(); $('.testWindows').show(); } var download = 'https://dl.google.com/go/' + filename; var message = $( '

' + 'Your download should begin shortly. ' + 'If it does not, click this link.

' ); message.find('a').attr('href', download); message.insertAfter('#nav'); window.location = download; } function updateVersionTags() { var v = window.goVersion; if (/^go[0-9.]+$/.test(v)) { $('.versionTag') .empty() .text(v); $('.whereTag').hide(); } } function addPermalinks() { function addPermalink(source, parent) { var id = source.attr('id'); if (id == '' || id.indexOf('tmp_') === 0) { // Auto-generated permalink. return; } if (parent.find('> .permalink').length) { // Already attached. return; } parent .append(' ') .append($("").attr('href', '#' + id)); } $('#page .container') .find('h2[id], h3[id]') .each(function() { var el = $(this); addPermalink(el, el); }); $('#page .container') .find('dl[id]') .each(function() { var el = $(this); // Add the anchor to the "dt" element. addPermalink(el, el.find('> dt').first()); }); } $('.js-expandAll').click(function() { if ($(this).hasClass('collapsed')) { toggleExamples('toggle'); $(this).text('(Collapse All)'); } else { toggleExamples('toggleVisible'); $(this).text('(Expand All)'); } $(this).toggleClass('collapsed'); }); function toggleExamples(className) { // We need to explicitly iterate through divs starting with "example_" // to avoid toggling Overview and Index collapsibles. $("[id^='example_']").each(function() { // Check for state and click it only if required. if ($(this).hasClass(className)) { $(this) .find('.toggleButton') .first() .click(); } }); } $(document).ready(function() { generateTOC(); addPermalinks(); bindToggles('.toggle'); bindToggles('.toggleVisible'); bindToggleLinks('.exampleLink', 'example_'); bindToggleLinks('.overviewLink', ''); bindToggleLinks('.examplesLink', ''); bindToggleLinks('.indexLink', ''); setupDropdownPlayground(); setupInlinePlayground(); fixFocus(); setupTypeInfo(); setupCallgraphs(); toggleHash(); personalizeInstallInstructions(); updateVersionTags(); // godoc.html defines window.initFuncs in the tag, and root.html and // codewalk.js push their on-page-ready functions to the list. // We execute those functions here, to avoid loading jQuery until the page // content is loaded. for (var i = 0; i < window.initFuncs.length; i++) window.initFuncs[i](); }); // -- analysis --------------------------------------------------------- // escapeHTML returns HTML for s, with metacharacters quoted. // It is safe for use in both elements and attributes // (unlike the "set innerText, read innerHTML" trick). function escapeHTML(s) { return s .replace(/&/g, '&') .replace(/\"/g, '"') .replace(/\'/g, ''') .replace(//g, '>'); } // makeAnchor returns HTML for an element, given an anchorJSON object. function makeAnchor(json) { var html = escapeHTML(json.Text); if (json.Href != '') { html = "" + html + ''; } return html; } function showLowFrame(html) { var lowframe = document.getElementById('lowframe'); lowframe.style.height = '200px'; lowframe.innerHTML = "

" + html + '

\n' + "
"; } document.hideLowFrame = function() { var lowframe = document.getElementById('lowframe'); lowframe.style.height = '0px'; }; // onClickCallers is the onclick action for the 'func' tokens of a // function declaration. document.onClickCallers = function(index) { var data = document.ANALYSIS_DATA[index]; if (data.Callers.length == 1 && data.Callers[0].Sites.length == 1) { document.location = data.Callers[0].Sites[0].Href; // jump to sole caller return; } var html = 'Callers of ' + escapeHTML(data.Callee) + ':
\n'; for (var i = 0; i < data.Callers.length; i++) { var caller = data.Callers[i]; html += '' + escapeHTML(caller.Func) + ''; var sites = caller.Sites; if (sites != null && sites.length > 0) { html += ' at line '; for (var j = 0; j < sites.length; j++) { if (j > 0) { html += ', '; } html += '' + makeAnchor(sites[j]) + ''; } } html += '
\n'; } showLowFrame(html); }; // onClickCallees is the onclick action for the '(' token of a function call. document.onClickCallees = function(index) { var data = document.ANALYSIS_DATA[index]; if (data.Callees.length == 1) { document.location = data.Callees[0].Href; // jump to sole callee return; } var html = 'Callees of this ' + escapeHTML(data.Descr) + ':
\n'; for (var i = 0; i < data.Callees.length; i++) { html += '' + makeAnchor(data.Callees[i]) + '
\n'; } showLowFrame(html); }; // onClickTypeInfo is the onclick action for identifiers declaring a named type. document.onClickTypeInfo = function(index) { var data = document.ANALYSIS_DATA[index]; var html = 'Type ' + data.Name + ': ' + '      (size=' + data.Size + ', align=' + data.Align + ')
\n'; html += implementsHTML(data); html += methodsetHTML(data); showLowFrame(html); }; // implementsHTML returns HTML for the implements relation of the // specified TypeInfoJSON value. function implementsHTML(info) { var html = ''; if (info.ImplGroups != null) { for (var i = 0; i < info.ImplGroups.length; i++) { var group = info.ImplGroups[i]; var x = '' + escapeHTML(group.Descr) + ' '; for (var j = 0; j < group.Facts.length; j++) { var fact = group.Facts[j]; var y = '' + makeAnchor(fact.Other) + ''; if (fact.ByKind != null) { html += escapeHTML(fact.ByKind) + ' type ' + y + ' implements ' + x; } else { html += x + ' implements ' + y; } html += '
\n'; } } } return html; } // methodsetHTML returns HTML for the methodset of the specified // TypeInfoJSON value. function methodsetHTML(info) { var html = ''; if (info.Methods != null) { for (var i = 0; i < info.Methods.length; i++) { html += '' + makeAnchor(info.Methods[i]) + '
\n'; } } return html; } // onClickComm is the onclick action for channel "make" and "<-" // send/receive tokens. document.onClickComm = function(index) { var ops = document.ANALYSIS_DATA[index].Ops; if (ops.length == 1) { document.location = ops[0].Op.Href; // jump to sole element return; } var html = 'Operations on this channel:
\n'; for (var i = 0; i < ops.length; i++) { html += makeAnchor(ops[i].Op) + ' by ' + escapeHTML(ops[i].Fn) + '
\n'; } if (ops.length == 0) { html += '(none)
\n'; } showLowFrame(html); }; $(window).load(function() { // Scroll window so that first selection is visible. // (This means we don't need to emit id='L%d' spans for each line.) // TODO(adonovan): ideally, scroll it so that it's under the pointer, // but I don't know how to get the pointer y coordinate. var elts = document.getElementsByClassName('selection'); if (elts.length > 0) { elts[0].scrollIntoView(); } }); // setupTypeInfo populates the "Implements" and "Method set" toggle for // each type in the package doc. function setupTypeInfo() { for (var i in document.ANALYSIS_DATA) { var data = document.ANALYSIS_DATA[i]; var el = document.getElementById('implements-' + i); if (el != null) { // el != null => data is TypeInfoJSON. if (data.ImplGroups != null) { el.innerHTML = implementsHTML(data); el.parentNode.parentNode.style.display = 'block'; } } var el = document.getElementById('methodset-' + i); if (el != null) { // el != null => data is TypeInfoJSON. if (data.Methods != null) { el.innerHTML = methodsetHTML(data); el.parentNode.parentNode.style.display = 'block'; } } } } function setupCallgraphs() { if (document.CALLGRAPH == null) { return; } document.getElementById('pkg-callgraph').style.display = 'block'; var treeviews = document.getElementsByClassName('treeview'); for (var i = 0; i < treeviews.length; i++) { var tree = treeviews[i]; if (tree.id == null || tree.id.indexOf('callgraph-') != 0) { continue; } var id = tree.id.substring('callgraph-'.length); $(tree).treeview({ collapsed: true, animated: 'fast' }); document.cgAddChildren(tree, tree, [id]); tree.parentNode.parentNode.style.display = 'block'; } } document.cgAddChildren = function(tree, ul, indices) { if (indices != null) { for (var i = 0; i < indices.length; i++) { var li = cgAddChild(tree, ul, document.CALLGRAPH[indices[i]]); if (i == indices.length - 1) { $(li).addClass('last'); } } } $(tree).treeview({ animated: 'fast', add: ul }); }; // cgAddChild adds an
  • element for document.CALLGRAPH node cgn to // the parent
      element ul. tree is the tree's root
        element. function cgAddChild(tree, ul, cgn) { var li = document.createElement('li'); ul.appendChild(li); li.className = 'closed'; var code = document.createElement('code'); if (cgn.Callees != null) { $(li).addClass('expandable'); // Event handlers and innerHTML updates don't play nicely together, // hence all this explicit DOM manipulation. var hitarea = document.createElement('div'); hitarea.className = 'hitarea expandable-hitarea'; li.appendChild(hitarea); li.appendChild(code); var childUL = document.createElement('ul'); li.appendChild(childUL); childUL.setAttribute('style', 'display: none;'); var onClick = function() { document.cgAddChildren(tree, childUL, cgn.Callees); hitarea.removeEventListener('click', onClick); }; hitarea.addEventListener('click', onClick); } else { li.appendChild(code); } code.innerHTML += ' ' + makeAnchor(cgn.Func); return li; } })(); Packages - Go Documentation Server
        ...

        Packages

        Standard library ▾

        Name Synopsis
        archive
        tar Package tar implements access to tar archives.
        zip Package zip provides support for reading and writing ZIP archives.
        arena The arena package provides the ability to allocate memory for a collection of Go values and free that space manually all at once, safely.
        bufio Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.
        builtin Package builtin provides documentation for Go's predeclared identifiers.
        bytes Package bytes implements functions for the manipulation of byte slices.
        cmp Package cmp provides types and functions related to comparing ordered values.
        compress
        bzip2 Package bzip2 implements bzip2 decompression.
        flate Package flate implements the DEFLATE compressed data format, described in RFC 1951.
        gzip Package gzip implements reading and writing of gzip format compressed files, as specified in RFC 1952.
        lzw Package lzw implements the Lempel-Ziv-Welch compressed data format, described in T. A. Welch, “A Technique for High-Performance Data Compression”, Computer, 17(6) (June 1984), pp 8-19.
        zlib Package zlib implements reading and writing of zlib format compressed data, as specified in RFC 1950.
        container
        heap Package heap provides heap operations for any type that implements heap.Interface.
        list Package list implements a doubly linked list.
        ring Package ring implements operations on circular lists.
        context Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
        crypto Package crypto collects common cryptographic constants.
        aes Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.
        boring Package boring exposes functions that are only available when building with Go+BoringCrypto.
        cipher Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations.
        des Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3.
        dsa Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.
        ecdh Package ecdh implements Elliptic Curve Diffie-Hellman over NIST curves and Curve25519.
        ecdsa Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-4 and SEC 1, Version 2.0.
        ed25519 Package ed25519 implements the Ed25519 signature algorithm.
        elliptic Package elliptic implements the standard NIST P-224, P-256, P-384, and P-521 elliptic curves over prime fields.
        hmac Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198.
        md5 Package md5 implements the MD5 hash algorithm as defined in RFC 1321.
        rand Package rand implements a cryptographically secure random number generator.
        rc4 Package rc4 implements RC4 encryption, as defined in Bruce Schneier's Applied Cryptography.
        rsa Package rsa implements RSA encryption as specified in PKCS #1 and RFC 8017.
        sha1 Package sha1 implements the SHA-1 hash algorithm as defined in RFC 3174.
        sha256 Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.
        sha512 Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.
        subtle Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.
        tls Package tls partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.
        fipsonly Package fipsonly restricts all TLS configuration to FIPS-approved settings.
        x509 Package x509 implements a subset of the X.509 standard.
        pkix Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.
        database
        sql Package sql provides a generic interface around SQL (or SQL-like) databases.
        driver Package driver defines interfaces to be implemented by database drivers as used by package sql.
        debug
        buildinfo Package buildinfo provides access to information embedded in a Go binary about how it was built.
        dwarf Package dwarf provides access to DWARF debugging information loaded from executable files, as defined in the DWARF 2.0 Standard at http://dwarfstd.org/doc/dwarf-2.0.0.pdf.
        elf Package elf implements access to ELF object files.
        gosym Package gosym implements access to the Go symbol and line number tables embedded in Go binaries generated by the gc compilers.
        macho Package macho implements access to Mach-O object files.
        pe Package pe implements access to PE (Microsoft Windows Portable Executable) files.
        plan9obj Package plan9obj implements access to Plan 9 a.out object files.
        embed Package embed provides access to files embedded in the running Go program.
        encoding Package encoding defines interfaces shared by other packages that convert data to and from byte-level and textual representations.
        ascii85 Package ascii85 implements the ascii85 data encoding as used in the btoa tool and Adobe's PostScript and PDF document formats.
        asn1 Package asn1 implements parsing of DER-encoded ASN.1 data structures, as defined in ITU-T Rec X.690.
        base32 Package base32 implements base32 encoding as specified by RFC 4648.
        base64 Package base64 implements base64 encoding as specified by RFC 4648.
        binary Package binary implements simple translation between numbers and byte sequences and encoding and decoding of varints.
        csv Package csv reads and writes comma-separated values (CSV) files.
        gob Package gob manages streams of gobs - binary values exchanged between an [Encoder] (transmitter) and a [Decoder] (receiver).
        hex Package hex implements hexadecimal encoding and decoding.
        json Package json implements encoding and decoding of JSON as defined in RFC 7159.
        pem Package pem implements the PEM data encoding, which originated in Privacy Enhanced Mail.
        xml Package xml implements a simple XML 1.0 parser that understands XML name spaces.
        errors Package errors implements functions to manipulate errors.
        expvar Package expvar provides a standardized interface to public variables, such as operation counters in servers.
        flag Package flag implements command-line flag parsing.
        fmt Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
        go
        ast Package ast declares the types used to represent syntax trees for Go packages.
        build Package build gathers information about Go packages.
        constraint Package constraint implements parsing and evaluation of build constraint lines.
        constant Package constant implements Values representing untyped Go constants and their corresponding operations.
        doc Package doc extracts source code documentation from a Go AST.
        comment Package comment implements parsing and reformatting of Go doc comments, (documentation comments), which are comments that immediately precede a top-level declaration of a package, const, func, type, or var.
        format Package format implements standard formatting of Go source.
        importer Package importer provides access to export data importers.
        parser Package parser implements a parser for Go source files.
        printer Package printer implements printing of AST nodes.
        scanner Package scanner implements a scanner for Go source text.
        token Package token defines constants representing the lexical tokens of the Go programming language and basic operations on tokens (printing, predicates).
        types Package types declares the data types and implements the algorithms for type-checking of Go packages.
        version Package version provides operations on [Go versions] in [Go toolchain name syntax]: strings like "go1.20", "go1.21.0", "go1.22rc2", and "go1.23.4-bigcorp".
        goberkeley
        berkeley
        hash Package hash provides interfaces for hash functions.
        adler32 Package adler32 implements the Adler-32 checksum.
        crc32 Package crc32 implements the 32-bit cyclic redundancy check, or CRC-32, checksum.
        crc64 Package crc64 implements the 64-bit cyclic redundancy check, or CRC-64, checksum.
        fnv Package fnv implements FNV-1 and FNV-1a, non-cryptographic hash functions created by Glenn Fowler, Landon Curt Noll, and Phong Vo.
        maphash Package maphash provides hash functions on byte sequences.
        html Package html provides functions for escaping and unescaping HTML text.
        template Package template (html/template) implements data-driven templates for generating HTML output safe against code injection.
        image Package image implements a basic 2-D image library.
        color Package color implements a basic color library.
        palette Package palette provides standard color palettes.
        draw Package draw provides image composition functions.
        gif Package gif implements a GIF image decoder and encoder.
        jpeg Package jpeg implements a JPEG image decoder and encoder.
        png Package png implements a PNG image decoder and encoder.
        index
        suffixarray Package suffixarray implements substring search in logarithmic time using an in-memory suffix array.
        io Package io provides basic interfaces to I/O primitives.
        fs Package fs defines basic interfaces to a file system.
        ioutil Package ioutil implements some I/O utility functions.
        iter Package iter provides basic definitions and operations related to iteration in Go.
        log Package log implements a simple logging package.
        slog Package slog provides structured logging, in which log records include a message, a severity level, and various other attributes expressed as key-value pairs.
        syslog Package syslog provides a simple interface to the system log service.
        maps Package maps defines various functions useful with maps of any type.
        math Package math provides basic constants and mathematical functions.
        big Package big implements arbitrary-precision arithmetic (big numbers).
        bits Package bits implements bit counting and manipulation functions for the predeclared unsigned integer types.
        cmplx Package cmplx provides basic constants and mathematical functions for complex numbers.
        rand Package rand implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.
        v2 Package rand implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.
        mime Package mime implements parts of the MIME spec.
        multipart Package multipart implements MIME multipart parsing, as defined in RFC 2046.
        quotedprintable Package quotedprintable implements quoted-printable encoding as specified by RFC 2045.
        net Package net provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.
        http Package http provides HTTP client and server implementations.
        cgi Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.
        cookiejar Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
        fcgi Package fcgi implements the FastCGI protocol.
        httptest Package httptest provides utilities for HTTP testing.
        httptrace Package httptrace provides mechanisms to trace the events within HTTP client requests.
        httputil Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package.
        pprof Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
        mail Package mail implements parsing of mail messages.
        netip Package netip defines an IP address type that's a small value type.
        rpc Package rpc provides access to the exported methods of an object across a network or other I/O connection.
        jsonrpc Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package.
        smtp Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
        textproto Package textproto implements generic support for text-based request/response protocols in the style of HTTP, NNTP, and SMTP.
        url Package url parses URLs and implements query escaping.
        os Package os provides a platform-independent interface to operating system functionality.
        exec Package exec runs external commands.
        signal Package signal implements access to incoming signals.
        user Package user allows user account lookups by name or id.
        path Package path implements utility routines for manipulating slash-separated paths.
        filepath Package filepath implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file paths.
        plugin Package plugin implements loading and symbol resolution of Go plugins.
        reflect Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types.
        regexp Package regexp implements regular expression search.
        syntax Package syntax parses regular expressions into parse trees and compiles parse trees into programs.
        runtime Package runtime contains operations that interact with Go's runtime system, such as functions to control goroutines.
        asan
        cgo Package cgo contains runtime support for code generated by the cgo tool.
        coverage
        debug Package debug contains facilities for programs to debug themselves while they are running.
        metrics Package metrics provides a stable interface to access implementation-defined metrics exported by the Go runtime.
        msan
        pprof Package pprof writes runtime profiling data in the format expected by the pprof visualization tool.
        race Package race implements data race detection logic.
        trace Package trace contains facilities for programs to generate traces for the Go execution tracer.
        slices Package slices defines various functions useful with slices of any type.
        sort Package sort provides primitives for sorting slices and user-defined collections.
        strconv Package strconv implements conversions to and from string representations of basic data types.
        strings Package strings implements simple functions to manipulate UTF-8 encoded strings.
        sync Package sync provides basic synchronization primitives such as mutual exclusion locks.
        atomic Package atomic provides low-level atomic memory primitives useful for implementing synchronization algorithms.
        syscall Package syscall contains an interface to the low-level operating system primitives.
        js Package js gives access to the WebAssembly host environment when using the js/wasm architecture.
        testing Package testing provides support for automated testing of Go packages.
        fstest Package fstest implements support for testing implementations and users of file systems.
        iotest Package iotest implements Readers and Writers useful mainly for testing.
        quick Package quick implements utility functions to help with black box testing.
        slogtest Package slogtest implements support for testing implementations of log/slog.Handler.
        text
        scanner Package scanner provides a scanner and tokenizer for UTF-8-encoded text.
        tabwriter Package tabwriter implements a write filter (tabwriter.Writer) that translates tabbed columns in input into properly aligned text.
        template Package template implements data-driven templates for generating textual output.
        parse Package parse builds parse trees for templates as defined by text/template and html/template.
        time Package time provides functionality for measuring and displaying time.
        tzdata Package tzdata provides an embedded copy of the timezone database.
        unicode Package unicode provides data and functions to test some properties of Unicode code points.
        utf16 Package utf16 implements encoding and decoding of UTF-16 sequences.
        utf8 Package utf8 implements functions and constants to support text encoded in UTF-8.
        unsafe Package unsafe contains operations that step around the type safety of Go programs.

        Third party ▾

        Name Synopsis
        github.com
        davecgh
        go-spew
        spew Package spew implements a deep pretty printer for Go data structures to aid in debugging.
        pebbe
        zmq4 A Go interface to ZeroMQ (zmq, 0mq) version 4.
        draft A Go interface to ZeroMQ (zmq, 0mq) version 4.
        examples_security
        pmezard
        go-difflib
        difflib Package difflib is a partial port of Python difflib module.
        sirupsen
        logrus Package logrus is a structured logger for Go, completely API compatible with the standard library logger.
        hooks
        syslog
        test The Test package is used for testing logrus.
        writer
        stretchr
        testify ** We are working on testify v2 and would love to hear what you'd like to see in it, have your say here: https://cutt.ly/testify ** Package testify is a set of packages that provide many tools for testifying that your code will behave as you intend.
        assert Package assert provides a set of comprehensive testing tools for use with the normal Go testing system.
        http Package http DEPRECATED USE net/http/httptest
        mock Package mock provides a system by which it is possible to mock your objects and verify calls are happening as expected.
        require Package require implements the same assertions as the `assert` package but stops test execution when a test fails.
        suite Package suite contains logic for creating testing suite structs and running the methods on those structs as tests.
        golang.org
        x
        sys
        cpu Package cpu implements processor feature detection for various CPU architectures.
        execabs Package execabs is a drop-in replacement for os/exec that requires PATH lookups to find absolute paths.
        plan9 Package plan9 contains an interface to the low-level operating system primitives.
        unix Package unix contains an interface to the low-level operating system primitives.
        linux
        windows Package windows contains an interface to the low-level operating system primitives.
        mkwinsyscall mkwinsyscall generates windows system call bodies
        registry Package registry provides access to the Windows registry.
        svc Package svc provides everything required to build Windows service.
        debug Package debug provides facilities to execute svc.Handler on console.
        eventlog Package eventlog implements access to Windows event log.
        example Example service program that beeps.
        mgr Package mgr can be used to manage Windows service programs.
        gopkg.in
        yaml.v3 Package yaml implements YAML support for the Go language.

        Other packages

        Sub-repositories

        These packages are part of the Go Project but outside the main Go tree. They are developed under looser compatibility requirements than the Go core. Install them with "go get".

        • benchmarks — benchmarks to measure Go as it is developed.
        • blogblog.golang.org's implementation.
        • buildbuild.golang.org's implementation.
        • crypto — additional cryptography packages.
        • debug — an experimental debugger for Go.
        • image — additional imaging packages.
        • mobile — experimental support for Go on mobile platforms.
        • net — additional networking packages.
        • perf — packages and tools for performance measurement, storage, and analysis.
        • pkgsite — home of the pkg.go.dev website.
        • review — a tool for working with Gerrit code reviews.
        • sync — additional concurrency primitives.
        • sys — packages for making system calls.
        • text — packages for working with text.
        • time — additional time packages.
        • tools — godoc, goimports, gorename, and other tools.
        • tourtour.golang.org's implementation.
        • exp — experimental and deprecated packages (handle with care; may change without warning).

        Community

        These services can help you find Open Source packages provided by the community.

        src/goberkeley/berkeley/anode.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/anode.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"errors"
             5  	"log"
             6  	"time"
             7  
             8  	zmq "github.com/pebbe/zmq4" // Librería para trabajar con ZeroMQ
             9  )
            10  
            11  // Interfaz Handler con el método HandleProcess
            12  type Handler interface {
            13  	HandleProcess(message string) (string, error)
            14  }
            15  
            16  // AbstractNode proporciona la funcionalidad base para nodos en el sistema.
            17  type AbstractNode struct {
            18  	Name          string
            19  	Address       string
            20  	Timeout       time.Duration
            21  	NodeAddresses map[string]string
            22  	Context       *zmq.Context
            23  	Socket        *zmq.Socket
            24  	Logger        *log.Logger
            25  	Handler       // Composición de la interfaz Handler
            26  }
            27  
            28  // NewAbstractNode crea e inicializa un nuevo nodo base.
            29  func NewAbstractNode(name, address string, timeout time.Duration) (*AbstractNode, error) {
            30  	context, err := zmq.NewContext()
            31  	if err != nil {
            32  		return nil, errors.New("error al crear el contexto ZeroMQ")
            33  	}
            34  
            35  	return &AbstractNode{
            36  		Name:    name,
            37  		Address: address,
            38  		Timeout: timeout,
            39  		Context: context,
            40  		Logger:  log.Default(),
            41  	}, nil
            42  }
            43  
            44  // InitializeNodeWithAddresses inicializa un nodo con direcciones de otros nodos.
            45  func InitializeNodeWithAddresses(name, address string, timeout time.Duration, addresses map[string]string) (*AbstractNode, error) {
            46  	var n *AbstractNode
            47  	n, err := NewAbstractNode(name, address, timeout)
            48  	if err != nil {
            49  		return nil, err
            50  	}
            51  	n.NodeAddresses = addresses
            52  	n.Logger.Printf("Nodo %s inicializado con direcciones %v", n.Name, addresses)
            53  	return n, nil
            54  }
            55  
            56  // SendMessageSync envía un mensaje de forma síncrona y espera una respuesta.
            57  func (n *AbstractNode) SendMessageSync(address string, message string) (string, error) {
            58  	// Creación del socket REQ (Request) para enviar el mensaje
            59  	var socket *zmq.Socket
            60  	socket, err := n.Context.NewSocket(zmq.REQ)
            61  	if err != nil {
            62  		n.Logger.Printf("Error al crear el socket REQ: %v", err) // Traza adicional
            63  		return "", errors.New("error al crear el socket REQ")
            64  	}
            65  	defer socket.Close()
            66  
            67  	// Establecer el timeout para recibir respuestas
            68  	socket.SetRcvtimeo(n.Timeout * time.Millisecond) // Convertir el timeout a milisegundos
            69  
            70  	// Traza: Mostrar el valor del timeout configurado
            71  	n.Logger.Printf("Timeout de recepción configurado a: %v milisegundos", int64(n.Timeout)) // Traza para el timeout
            72  
            73  	// Conectar al socket en la dirección proporcionada
            74  	err = socket.Connect("tcp://" + address)
            75  	if err != nil {
            76  		n.Logger.Printf("Error al conectar con %s: %v", address, err) // Traza adicional
            77  		return "", errors.New("error al conectar con " + address)
            78  	}
            79  
            80  	n.Logger.Printf("Conectado a %s", address) // Traza para verificar la conexión
            81  
            82  	// Enviar el mensaje al servidor
            83  	_, err = socket.Send(message, 0)
            84  	if err != nil {
            85  		n.Logger.Printf("Error al enviar el mensaje a %s: %v", address, err) // Traza adicional
            86  		return "", errors.New("error al enviar el mensaje")
            87  	}
            88  
            89  	n.Logger.Printf("Mensaje enviado a %s: %s", address, message) // Traza de envío
            90  
            91  	// Intentar recibir la respuesta
            92  	reply, err := socket.Recv(0)
            93  	if err != nil {
            94  		n.Logger.Printf("Error al recibir respuesta de %s: %v", address, err) // Traza para el error de recepción
            95  		return "", errors.New("no se recibió respuesta del socket")
            96  	}
            97  
            98  	n.Logger.Printf("Respuesta recibida de %s: %s", address, reply) // Traza de respuesta recibida
            99  	return reply, nil
           100  }
           101  
           102  // SendMessageAsync envía un mensaje de manera asíncrona.
           103  func (n *AbstractNode) SendMessageAsync(address, message string) error {
           104  	socket, err := n.Context.NewSocket(zmq.PUSH)
           105  	if err != nil {
           106  		return errors.New("error al crear el socket PUSH")
           107  	}
           108  	defer socket.Close()
           109  
           110  	err = socket.Connect("tcp://" + address)
           111  	if err != nil {
           112  		return errors.New("error al conectar con " + address)
           113  	}
           114  
           115  	_, err = socket.Send(message, 0)
           116  	if err != nil {
           117  		return errors.New("error al enviar el mensaje")
           118  	}
           119  
           120  	n.Logger.Printf("Mensaje asincrónico enviado a %s: %s", address, message)
           121  	return nil
           122  }
           123  
           124  // StartListening inicia el proceso de escucha para mensajes entrantes en el nodo.
           125  // Configura un socket de tipo REP (Response) para recibir y responder a mensajes.
           126  func (n *AbstractNode) StartListening() error {
           127  	// Log para indicar que estamos intentando crear un socket REP.
           128  	n.Logger.Printf("Intentando crear un socket REP para el nodo %s en la dirección %s", n.Name, n.Address)
           129  	socket, err := n.Context.NewSocket(zmq.REP)
           130  	if err != nil {
           131  		// Si ocurre un error al crear el socket, loguea el error y retorna un mensaje de error.
           132  		n.Logger.Printf("Error al crear el socket REP: %v", err)
           133  		return errors.New("error al crear el socket REP")
           134  	}
           135  	n.Socket = socket
           136  	n.Logger.Printf("Socket REP creado exitosamente para el nodo %s", n.Name)
           137  
           138  	// Enlaza el socket a la dirección TCP proporcionada en el nodo para esperar conexiones.
           139  	n.Logger.Printf("Enlazando el socket REP en la dirección tcp://%s", n.Address)
           140  	err = socket.Bind("tcp://" + n.Address)
           141  	if err != nil {
           142  		// Si ocurre un error al enlazar el socket, loguea el error y retorna un mensaje de error.
           143  		n.Logger.Printf("Error al enlazar el socket en %s: %v", n.Address, err)
           144  		return errors.New("error al enlazar el socket en " + n.Address)
           145  	}
           146  	n.Logger.Printf("Socket enlazado exitosamente en %s", n.Address)
           147  
           148  	// Inicia una nueva goroutine para escuchar de manera concurrente sin bloquear el hilo principal.
           149  	n.Logger.Printf("Iniciando goroutine para escuchar en el nodo %s", n.Name)
           150  	go func() {
           151  		// Logea que el nodo ha comenzado a escuchar en la dirección configurada.
           152  		n.Logger.Printf("Nodo %s escuchando en %s", n.Name, n.Address)
           153  
           154  		// Entra en un bucle infinito para recibir y procesar mensajes.
           155  		for {
           156  			// Recibe un mensaje del socket.
           157  			n.Logger.Printf("Esperando mensaje en %s...", n.Name)
           158  			message, err := socket.Recv(0)
           159  			if err != nil {
           160  				// Si ocurre un error al recibir el mensaje, loguea el error y termina el bucle.
           161  				n.Logger.Printf("Error al recibir mensaje: %v", err)
           162  				break
           163  			}
           164  			n.Logger.Printf("Mensaje recibido en %s: %v", n.Name, message)
           165  
           166  			// Llama al método HandleProcess, que es implementado por el tipo real de nodo (Follower, Leader, etc.).
           167  			// Este método procesará el mensaje recibido y generará una respuesta.
           168  			n.Logger.Printf("Procesando mensaje en %s...", n.Name)
           169  			response, err := n.Handler.HandleProcess(message)
           170  			if err != nil {
           171  				// Si hay un error al procesar el mensaje, loguea el error y termina el bucle.
           172  				n.Logger.Printf("Error en HandleProcess en %s: %v", n.Name, err)
           173  				break
           174  			}
           175  
           176  			// Envía la respuesta de vuelta al cliente a través del socket.
           177  			n.Logger.Printf("Enviando respuesta en %s: %v", n.Name, response)
           178  			_, err = socket.Send(response, 0)
           179  			if err != nil {
           180  				// Si ocurre un error al enviar la respuesta, loguea el error y termina el bucle.
           181  				n.Logger.Printf("Error al enviar respuesta en %s: %v", n.Name, err)
           182  				break
           183  			}
           184  		}
           185  	}()
           186  
           187  	// La función regresa nil si todo se configura correctamente y la goroutine se inicia sin errores.
           188  	n.Logger.Printf("Escucha iniciada exitosamente en el nodo %s", n.Name)
           189  	return nil
           190  }
           191  
           192  // Close cierra los recursos del nodo.
           193  func (n *AbstractNode) Close() error {
           194  	if n.Socket != nil {
           195  		n.Socket.Close()
           196  		n.Logger.Printf("Socket cerrado para el nodo %s", n.Name)
           197  	}
           198  	if n.Context != nil {
           199  		n.Context.Term()
           200  		n.Logger.Printf("Contexto cerrado para el nodo %s", n.Name)
           201  	}
           202  	return nil
           203  }
           204  
           205  // handleProcess debe ser sobrescrito por las subclases para procesar mensajes.
           206  func (n *AbstractNode) handleProcess(message string) string {
           207  	n.Logger.Printf("Procesando mensaje: %s", message)
           208  	return `{"status":"unhandled"}`
           209  }
           210  
        

        View as plain text

        src/goberkeley/berkeley/config.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/config.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  	"os"
             7  	"time"
             8  )
             9  
            10  type LeaderConfig struct {
            11  	Name    string `json:"name"`
            12  	Address string `json:"address"`
            13  }
            14  
            15  type FollowerConfig struct {
            16  	Name    string `json:"name"`
            17  	Address string `json:"address"`
            18  }
            19  
            20  type Config struct {
            21  	Leader    LeaderConfig     `json:"leader"`
            22  	Followers []FollowerConfig `json:"followers"`
            23  	Timeout   time.Duration    `json:"timeout"`
            24  }
            25  
            26  func LoadConfig(filepath string) *Config {
            27  	// Abrir el archivo JSON
            28  	file, err := os.Open(filepath)
            29  	if err != nil {
            30  		fmt.Println("Error abriendo el archivo:", err)
            31  		return nil
            32  	}
            33  	defer file.Close()
            34  
            35  	// Decodificar el JSON en la estructura Config
            36  	var config Config
            37  	decoder := json.NewDecoder(file)
            38  	if err := decoder.Decode(&config); err != nil {
            39  		fmt.Println("Error decodificando JSON:", err)
            40  		return nil
            41  	}
            42  
            43  	// Imprimir la configuración cargada
            44  	fmt.Printf("Líder: %s (%s)\n", config.Leader.Name, config.Leader.Address)
            45  	for _, follower := range config.Followers {
            46  		fmt.Printf("Seguidor: %s (%s)\n", follower.Name, follower.Address)
            47  	}
            48  	fmt.Printf("Timeout: %d ms\n", config.Timeout)
            49  
            50  	return &config
            51  }
            52  
        

        View as plain text

        src/goberkeley/berkeley/follower.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"errors"
             6  	"fmt"
             7  	"log"
             8  	"time"
             9  )
            10  
            11  // Follower representa un nodo seguidor en el sistema distribuido.
            12  type Follower struct {
            13  	aAbstractNode *AbstractNode
            14  	LeaderAddress string
            15  }
            16  
            17  // InitializeNode inicializa el nodo seguidor con su información específica.
            18  func InitializeFollowerNode(name, address, leaderAddress string, timeout time.Duration) (*Follower, error) {
            19  	// Asegúrate de llamar al método correcto de AbstractNode.
            20  
            21  	f, err := NewFollower(name, address, leaderAddress, timeout)
            22  	if err != nil {
            23  		return nil, err
            24  	}
            25  
            26  	return f, nil
            27  }
            28  
            29  // NewFollower crea e inicializa un nuevo nodo seguidor.
            30  func NewFollower(name, address, leaderAddress string, timeout time.Duration) (*Follower, error) {
            31  	// Inicializar el nodo abstracto usando NewAbstractNode
            32  	abstractNode, err := NewAbstractNode(name, address, timeout)
            33  	if err != nil {
            34  		return nil, err
            35  	}
            36  
            37  	// Crear e inicializar la estructura Follower
            38  	follower := &Follower{
            39  		aAbstractNode: abstractNode,
            40  		LeaderAddress: leaderAddress,
            41  	}
            42  	follower.aAbstractNode.Handler = follower
            43  	return follower, nil
            44  }
            45  
            46  // HandleProcess maneja y procesa los mensajes recibidos del líder.
            47  // Implementación de HandleProcess para Follower
            48  func (f *Follower) HandleProcess(message string) (string, error) {
            49  	log.Printf("Recibiendo mensaje del líder: %s", message) // Traza para ver el mensaje recibido
            50  
            51  	// Deserialización del mensaje JSON
            52  	var data map[string]interface{}
            53  	if err := json.Unmarshal([]byte(message), &data); err != nil {
            54  		log.Printf("Error al deserializar el mensaje JSON: %v", err)
            55  		return `{"error":"Error al procesar el mensaje JSON"}`, nil
            56  	}
            57  	log.Printf("Mensaje deserializado correctamente: %+v", data) // Traza para mostrar el mensaje deserializado
            58  
            59  	// Extraer los campos del mensaje deserializado
            60  	leaderAddr := data["leader_address"].(string)
            61  	operation := data["operation"].(string)
            62  	leaderMessage := data["message"].(string)
            63  
            64  	log.Printf("Procesando mensaje del líder: %s desde %s con operación: %s", leaderAddr, f.LeaderAddress, operation)
            65  
            66  	// Procesar según la operación especificada
            67  	switch operation {
            68  	case "GET_TIME":
            69  		// Acceder a 'time' y asegurar su tipo como float64
            70  		T0Float, ok := data["time"].(float64)
            71  		if !ok {
            72  			log.Printf("Error al convertir data[\"time\"] a float64")
            73  			return "", errors.New("Error al procesar el campo Time")
            74  		}
            75  
            76  		// Convertir de float64 a int64
            77  		T0 := int64(T0Float)
            78  
            79  		log.Printf("T0 recibido: %d", T0)
            80  		currentTime := f.getCurrentTime()
            81  
            82  		log.Printf("Operación GET_TIME: T0 recibido %d, Hora local calculada: %d", T0, currentTime) // Traza para tiempo
            83  
            84  		// Llamada a la función que maneja el mensaje del líder y muestra su mensaje
            85  		TP := f.displayLeaderMessage(leaderAddr, leaderMessage, T0, currentTime)
            86  		log.Printf("Hora procesada TP: %d", TP) // Traza para TP
            87  
            88  		// Responder con el formato esperado
            89  		return fmt.Sprintf(`{"followerName":"%s", "localTime":"%d", "addressFollower":"%s"}`, f.aAbstractNode.Name, TP, f.aAbstractNode.Address), nil
            90  	case "UPDATE_TIME":
            91  		delta := int64(data["delta"].(float64))
            92  		log.Printf("Operación UPDATE_TIME: Delta recibido: %d", delta) // Traza para delta
            93  
            94  		// Modificar el sistema según el delta
            95  		return f.modSystemTime(delta), nil
            96  	case "CLOSE":
            97  		log.Printf("Operación CLOSE: Cerrando seguidor %s", f.aAbstractNode.Name) // Traza para CLOSE
            98  		return fmt.Sprintf(`{"followerName":"%s","operation":"CLOSE"}`, f.aAbstractNode.Name), nil
            99  	default:
           100  		log.Printf("Operación no reconocida en el mensaje del líder: %s", operation) // Traza para operación no reconocida
           101  		return `{"error":"Operación no reconocida"}`, nil
           102  	}
           103  }
           104  
           105  // displayLeaderMessage muestra el mensaje del líder y calcula un tiempo promedio (TP).
           106  func (f *Follower) displayLeaderMessage(leaderAddr, leaderMessage string, T0, localTime int64) int64 {
           107  	log.Printf("Mensaje del líder con dirección (%s) recibido: %s con T0 %s", leaderAddr, leaderMessage, time.UnixMilli(T0).String())
           108  	TP := (T0 + localTime) / 2
           109  	log.Printf("TP del seguidor %s es %s", f.aAbstractNode.Name, time.UnixMilli(TP).String())
           110  	return TP
           111  }
           112  
           113  // modSystemTime modifica el tiempo local del sistema basado en un delta.
           114  func (f *Follower) modSystemTime(delta int64) string {
           115  	currentLocalTime := time.Now().UnixMilli()
           116  	modSystemTime := currentLocalTime + delta
           117  	log.Printf("Tiempo del seguidor %s modificado de %s a %s", f.aAbstractNode.Name, time.UnixMilli(currentLocalTime).String(), time.UnixMilli(modSystemTime).String())
           118  	return fmt.Sprintf(`{"followerName":"%s", "localTime":"%d","operation":"OK_MOD_TIME"}`, f.aAbstractNode.Name, modSystemTime)
           119  }
           120  
           121  // getCurrentTime obtiene la hora actual del sistema en milisegundos desde la época Unix.
           122  func (f *Follower) getCurrentTime() int64 {
           123  	TP := time.Now().UnixMilli()
           124  	log.Printf("Fecha y hora local del seguidor: TP: %s", time.UnixMilli(TP).String())
           125  	return TP
           126  }
           127  
           128  // StartAlgorithm configura e inicia el socket REP para escuchar mensajes entrantes
           129  // y delega la responsabilidad de iniciar la escucha al nodo abstracto.
           130  // StartAlgorithm configura e inicia la escucha en el seguidor
           131  func (f *Follower) StartAlgorithm() error {
           132  	// Llama a StartListening, que se encargará de la creación y enlace del socket.
           133  	log.Printf("Iniciando algoritmo para el seguidor %s en %s", f.aAbstractNode.Name, f.aAbstractNode.Address)
           134  	return f.aAbstractNode.StartListening()
           135  }
           136  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_state.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_state.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  // FollowerState representa los posibles estados de un seguidor durante el proceso de actualización de la hora del sistema.
             4  type FollowerState string
             5  
             6  const (
             7  	// RESPONDED indica que el seguidor ha respondido correctamente a la solicitud del líder.
             8  	Responded FollowerState = "RESPONDED"
             9  
            10  	// NO_RESPONSE indica que el seguidor no ha respondido a la solicitud dentro del tiempo esperado.
            11  	NoResponse FollowerState = "NO_RESPONSE"
            12  
            13  	// CONNECTION_ERROR indica que hubo un error de conexión al intentar comunicarse con el seguidor.
            14  	ConnectionError FollowerState = "CONNECTION_ERROR"
            15  
            16  	// REQUEST_NOT_SENT indica que la solicitud de actualización de la hora no fue enviada debido a algún error.
            17  	RequestNotSent FollowerState = "REQUEST_NOT_SENT"
            18  
            19  	// REQUEST_DELTA_SENT indica que la solicitud de actualización de la hora fue enviada al seguidor para actualizar su hora.
            20  	RequestDeltaSent FollowerState = "REQUEST_DELTA_SENT"
            21  
            22  	// TIME_ERROR_SENT_UPDATE indica que la solicitud de actualización de la hora fue enviada pero hubo un error en ese envío.
            23  	TimeErrorSentUpdate FollowerState = "TIME_ERROR_SENT_UPDATE"
            24  
            25  	// TIME_UPDATED indica que la hora del sistema del seguidor se actualizó correctamente.
            26  	TimeUpdated FollowerState = "TIME_UPDATED"
            27  
            28  	// ERROR_CLOSE indica que  no pude enviar el cierre del socket en el seguidor.
            29  	ErrorClose FollowerState = "ERROR_CLOSE"
            30  
            31  	// Ok_CLOSE indica que   pude  cerrar el socket en el seguidor.
            32  	OkClose FollowerState = "Ok_CLOSE"
            33  )
            34  
        

        View as plain text

        src/goberkeley/berkeley/inode.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/inode.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"time"
             5  )
             6  
             7  // INode define las operaciones básicas para un nodo en el sistema.
             8  type INode interface {
             9  	InitializeNode(name string, address string, timeout time.Duration) error
            10  	InitializeNodeWithAddresses(name string, address string, timeout time.Duration, addresses map[string]string) error
            11  	SendMessageSync(address string, message string) (string, error)
            12  	SendMessageAsync(address string, message string) error
            13  	StartListening() error
            14  	StartAlgorithm() error
            15  	Close() error
            16  }
            17  
        

        View as plain text

        src/goberkeley/berkeley/leader.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/leader.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  
             7  	"log"
             8  	"strconv"
             9  	"sync"
            10  	"time"
            11  )
            12  
            13  // Mensaje JSON que se envía al seguidor.
            14  type TimeRequest struct {
            15  	Message    string `json:"message"`
            16  	Operation  string `json:"operation"`
            17  	Time       int64  `json:"time"`
            18  	LeaderAddr string `json:"leader_address"`
            19  }
            20  type DeltaRequest struct {
            21  	Message    string `json:"message"`
            22  	Operation  string `json:"operation"`
            23  	Delta      int64  `json:"delta"`
            24  	LeaderAddr string `json:"leader_address"`
            25  }
            26  type closeRequest struct {
            27  	Message    string `json:"message"`
            28  	Operation  string `json:"operation"`
            29  	LeaderAddr string `json:"leader_address"`
            30  }
            31  
            32  // Leader representa el nodo líder en el sistema Berkeley.
            33  type Leader struct {
            34  	aAbstractNode          *AbstractNode
            35  	UnreachableFollowers   map[string]*FollowerInfo
            36  	SuccessfulFollowers    map[string]*FollowerInfo
            37  	NonRespondingFollowers map[string]*FollowerInfo
            38  	TimeUpdatedFollowers   map[string]*FollowerInfo
            39  	FailedFollowers        map[string]*FollowerInfo
            40  	//mu                     sync.Mutex // Mutex para proteger los mapas en accesos concurrentes
            41  	Logger *log.Logger
            42  }
            43  
            44  // HandleProcess implements Handler.
            45  func (l *Leader) HandleProcess(message string) (string, error) {
            46  	panic("unimplemented")
            47  }
            48  
            49  // InitializeLeaderNode crea e inicializa un nuevo nodo líder.
            50  func InitializeLeaderNode(name, address string, timeout time.Duration, nodeAddresses map[string]string) (*Leader, error) {
            51  	// Suponiendo que InitializeNodeWithAddresses crea un nodo base y devuelve un puntero a AbstractNode
            52  	baseNode, err := InitializeNodeWithAddresses(name, address, timeout, nodeAddresses)
            53  	if err != nil {
            54  		return nil, err
            55  	}
            56  
            57  	// Inicializamos el líder, asignando el nodo base y un logger
            58  	leader := &Leader{
            59  		aAbstractNode: baseNode, // Asignamos el puntero a AbstractNode
            60  		Logger:        log.Default(),
            61  	}
            62  	leader.aAbstractNode.Handler = leader
            63  
            64  	return leader, nil
            65  }
            66  func (l *Leader) initStructs() {
            67  	if l.UnreachableFollowers == nil {
            68  		l.UnreachableFollowers = make(map[string]*FollowerInfo)
            69  	}
            70  	if l.SuccessfulFollowers == nil {
            71  		l.SuccessfulFollowers = make(map[string]*FollowerInfo)
            72  	}
            73  	if l.NonRespondingFollowers == nil {
            74  		l.NonRespondingFollowers = make(map[string]*FollowerInfo)
            75  	}
            76  	if l.TimeUpdatedFollowers == nil {
            77  		l.TimeUpdatedFollowers = make(map[string]*FollowerInfo)
            78  	}
            79  	if l.FailedFollowers == nil {
            80  		l.FailedFollowers = make(map[string]*FollowerInfo)
            81  	}
            82  }
            83  
            84  // StartAlgorithm implementa el algoritmo de sincronización Berkeley para el líder.
            85  func (l *Leader) StartAlgorithm() {
            86  	l.Logger.Println("Iniciando algoritmo de sincronización Berkeley...")
            87  	l.initStructs()
            88  	// Simula el envío de solicitudes de tiempo a los seguidores
            89  	l.processFollowers()
            90  
            91  	// Fase 2: Calcular el delta con la media de los tiempos
            92  	log.Println("** Fase 2 **: Calcular el delta con la media de los tiempos")
            93  	delta := l.calculateDeltaTimeDifference()
            94  	if delta != 0 {
            95  		// Paso 3: Actualizar relojes de los seguidores
            96  		log.Println("** Paso 3 **: Llamar a los seguidores para actualizar sus relojes")
            97  		l.callFollowersWithUpdatedTime(delta)
            98  
            99  		// Fase 4: Enviar mensaje de cierre
           100  		log.Println("** Fase 4 **: Enviar mensaje de cierre a los seguidores")
           101  		l.sendCloseMessagesToFollowers()
           102  
           103  		// Fase 5: Mostrar los resultados finales
           104  		log.Println("** Fase 5: Mostrar los resultados de la sincronización")
           105  		l.printResults()
           106  	} else {
           107  		// Se registra esta situación para comprobarlo más adelante en los logs
           108  		log.Println("El resultado del delta es cero por lo que no se envían actualizaciones a ningún seguidor.")
           109  	}
           110  }
           111  func (l *Leader) processFollowers() {
           112  	leaderTime := time.Now().UnixMilli() // T0
           113  	leaderAddr := l.aAbstractNode.Address
           114  
           115  	log.Printf("processFollowers: leaderAddr %s leaderTime %d.", leaderAddr, leaderTime)
           116  
           117  	// Lista de seguidores
           118  	followers := l.aAbstractNode.NodeAddresses
           119  
           120  	// Canal para los resultados
           121  	results := make(chan *FollowerInfo, len(followers))
           122  	var wg sync.WaitGroup
           123  
           124  	// Enviar solicitudes a los seguidores concurrentemente
           125  	for followerName, followerAddr := range followers {
           126  		wg.Add(1)
           127  		go func(name, addr string) {
           128  			defer wg.Done()
           129  			log.Printf("Enviando solicitud de tiempo a %s (%s).", name, addr)
           130  			l.sendTimeRequestToFollower(name, addr, leaderTime, leaderAddr, results)
           131  		}(followerName, followerAddr)
           132  	}
           133  
           134  	// Cerrar el canal una vez que todos los goroutines hayan terminado
           135  	go func() {
           136  		wg.Wait()
           137  		close(results)
           138  	}()
           139  
           140  	// Recoger y procesar los resultados
           141  	for res := range results {
           142  		if res.GetState() == "RESPONDED" {
           143  			// Seguidor que respondió correctamente
           144  			l.SuccessfulFollowers[res.GetName()] = res
           145  			log.Printf("Seguidor %s respondió correctamente con tiempo local: %d ms", res.GetName(), res.GetLocalTime())
           146  		} else if res.GetState() == "TIMEOUT" {
           147  			// Seguidor que no respondió a tiempo
           148  			l.NonRespondingFollowers[res.GetName()] = res
           149  			log.Printf("Seguidor %s no respondió a tiempo.", res.GetName())
           150  		} else {
           151  			// Seguidor que tuvo algún otro problema
           152  			l.FailedFollowers[res.GetName()] = res
           153  			log.Printf("Seguidor %s falló con estado: %s.", res.GetName(), res.GetState())
           154  		}
           155  	}
           156  
           157  	// Log final para indicar que el procesamiento de seguidores ha terminado
           158  	log.Printf("Proceso de seguidores completado. Respuestas procesadas: %d, Fallos: %d.", len(l.SuccessfulFollowers), len(l.NonRespondingFollowers))
           159  }
           160  func (l *Leader) sendTimeRequestToFollower(followerName, followerAddr string, leaderTime int64, leaderAddr string, results chan<- *FollowerInfo) {
           161  	// Crear el mensaje JSON
           162  	request := TimeRequest{
           163  		Message:    "Requesting time sync",
           164  		Operation:  "GET_TIME",
           165  		Time:       leaderTime, //T0
           166  		LeaderAddr: leaderAddr,
           167  	}
           168  
           169  	// Serializar el mensaje en formato JSON
           170  	requestData, err := json.Marshal(request)
           171  	if err != nil {
           172  		log.Printf("Error al serializar la solicitud a JSON: %v", err)
           173  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           174  		return
           175  	}
           176  
           177  	// Convertir el JSON a string
           178  	requestString := string(requestData)
           179  	log.Printf("Solicitud enviada a %s: %s", followerAddr, requestString)
           180  
           181  	// Enviar el mensaje al seguidor y recibir la respuesta
           182  	reply, err := l.aAbstractNode.SendMessageSync(followerAddr, requestString)
           183  	if err != nil {
           184  		log.Printf("Error al recibir respuesta de %s: %v", followerAddr, err)
           185  		followError := NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           186  		results <- followError
           187  		return
           188  	}
           189  
           190  	log.Printf("Respuesta recibida de %s: %s", followerAddr, reply)
           191  
           192  	// Deserializar la respuesta JSON
           193  	var response map[string]string
           194  	if err := json.Unmarshal([]byte(reply), &response); err != nil {
           195  		log.Printf("Error al procesar la respuesta de %s: %v", followerAddr, err)
           196  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           197  		return
           198  	}
           199  
           200  	// Calcular la diferencia de tiempo
           201  	endCommTime := time.Now().UnixMilli() // T0
           202  	timeComm := endCommTime - leaderTime
           203  	log.Printf("Tiempo de comunicación: %d ms", timeComm)
           204  
           205  	// Obtener el tiempo local del seguidor
           206  	localTimeStr, ok := response["localTime"]
           207  	if !ok {
           208  		log.Printf("No se encontró el campo 'localTime' en la respuesta de %s", followerAddr)
           209  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           210  		return
           211  	}
           212  
           213  	// Convertir el valor de localTime de string a int64
           214  	localTimeInt64, err := strconv.ParseInt(localTimeStr, 10, 64)
           215  	if err != nil {
           216  		log.Printf("Error al convertir 'localTime' a int64 de %s: %v", followerAddr, err)
           217  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           218  		return
           219  	}
           220  
           221  	// Enviar los resultados al canal
           222  	log.Printf("Tiempo local recibido de %s: %d", followerAddr, localTimeInt64)
           223  	foll := NewFollowerInfo(followerAddr, followerName, localTimeInt64, timeComm, 0)
           224  	foll.SetState(Responded)
           225  	results <- foll
           226  }
           227  
           228  // calculateDeltaTimeDifference calcula la diferencia de tiempo (delta) entre el tiempo local y los tiempos de los seguidores válidos.
           229  func (l *Leader) calculateDeltaTimeDifference() int64 {
           230  	// Log de inicio de la operación de cálculo de la diferencia de tiempo
           231  	log.Println("Calculando la diferencia de tiempo (delta)")
           232  
           233  	// Obtener el tiempo actual del líder
           234  	now := time.Now().UnixMilli()
           235  	var sumTime int64 = 0           // Suma de los tiempos ajustados de los seguidores
           236  	var validFollowersCount int = 0 // Contador de seguidores con respuestas válidas
           237  
           238  	// Recorrer los seguidores exitosos y calcular la diferencia de tiempo para cada uno
           239  	for _, follower := range l.SuccessfulFollowers {
           240  		if follower.DiffTime != int64(^uint64(0)>>1) { // Verificar si el seguidor tiene un tiempo válido (Long.MAX_VALUE en Java)
           241  			followerTime := now + follower.DiffTime // Calcular el tiempo ajustado del seguidor
           242  			sumTime += followerTime                 // Sumar el tiempo ajustado
           243  			validFollowersCount++                   // Incrementar el contador de seguidores válidos
           244  		}
           245  	}
           246  
           247  	// Si se tienen seguidores válidos, calcular la diferencia de tiempo promedio
           248  	if validFollowersCount > 0 {
           249  		newNow := sumTime / int64(validFollowersCount) // Calcular el promedio de los tiempos de los seguidores
           250  		delta := newNow - now                          // Calcular la diferencia de tiempo (delta)
           251  
           252  		// Log de los resultados calculados
           253  		log.Printf("Nuevo tiempo calculado (new_now): %d\n", newNow)
           254  		log.Printf("Diferencia global (δ): %d\n", delta)
           255  
           256  		// Retornar la diferencia de tiempo (delta)
           257  		return delta
           258  	} else {
           259  		// Si no hay seguidores válidos, registrar advertencia y retornar 0
           260  		log.Println("No se han recibido respuestas válidas de los seguidores.")
           261  		return 0
           262  	}
           263  }
           264  
           265  func (l *Leader) callFollowersWithUpdatedTime(delta int64) error {
           266  	log.Printf("Enviando actualización de tiempo a los seguidores con delta: %d", delta)
           267  
           268  	// Crear un canal para gestionar las tareas concurrentes
           269  	ch := make(chan *FollowerInfo, len(l.SuccessfulFollowers))
           270  
           271  	// Usamos un WaitGroup para esperar que todas las goroutines terminen
           272  	var wg sync.WaitGroup
           273  
           274  	// Enviar las tareas en paralelo para cada seguidor
           275  	for _, follower := range l.SuccessfulFollowers {
           276  		wg.Add(1) // Incrementamos el contador del WaitGroup
           277  		go func(follower FollowerInfo) {
           278  			defer wg.Done() // Decrementamos el contador del WaitGroup cuando la goroutine termina
           279  			followerInfo := l.sendTimeUpdateToFollower(follower, delta)
           280  			ch <- followerInfo
           281  		}(*follower)
           282  	}
           283  
           284  	// Iniciar una goroutine para cerrar el canal una vez que todas las goroutines hayan terminado
           285  	go func() {
           286  		wg.Wait() // Esperamos a que todas las goroutines terminen
           287  		close(ch) // Cerramos el canal después de que todas las goroutines hayan enviado sus respuestas
           288  	}()
           289  
           290  	// Procesar las respuestas conforme vayan llegando
           291  	for followerInfo := range ch {
           292  		if followerInfo.State == "TIME_UPDATED" {
           293  			log.Printf("El seguidor %s respondió correctamente al cambio del timer.", followerInfo.Name)
           294  			l.TimeUpdatedFollowers[followerInfo.Name] = followerInfo
           295  		} else {
           296  			log.Printf("El seguidor %s no respondió al cambio de su timer.", followerInfo.Name)
           297  			l.FailedFollowers[followerInfo.Name] = followerInfo
           298  		}
           299  	}
           300  
           301  	return nil
           302  }
           303  
           304  func (l *Leader) sendTimeUpdateToFollower(follower FollowerInfo, delta int64) *FollowerInfo {
           305  
           306  	// Crear el mapa con la solicitud
           307  	request := DeltaRequest{
           308  		Message:    "Modifica el tiempo del sistema de tu servidor con el diferencial.",
           309  		Operation:  "UPDATE_TIME",
           310  		Delta:      delta,
           311  		LeaderAddr: l.aAbstractNode.Address,
           312  	}
           313  
           314  	// Serializar la solicitud a JSON
           315  	jsonRequest, err := json.Marshal(request)
           316  	if err != nil {
           317  		log.Printf("Error al serializar la solicitud para el seguidor %s: %v", follower.Name, err)
           318  		follower.State = TimeErrorSentUpdate
           319  		return &follower
           320  	}
           321  
           322  	requestString := string(jsonRequest)
           323  	log.Printf("Solicitud enviada a %s: %s", follower.GetAddress(), requestString)
           324  	// Enviar la solicitud
           325  	reply, err := l.aAbstractNode.SendMessageSync(follower.GetAddress(), requestString)
           326  	if err != nil {
           327  		log.Printf("Error al recibir respuesta de %s: %v", follower.GetAddress(), err)
           328  		followError := NewFollowerInfo(follower.GetAddress(), follower.GetName(), 0, 0, 0)
           329  		followError.State = TimeErrorSentUpdate
           330  		return followError
           331  	}
           332  
           333  	var response map[string]string
           334  	err = json.Unmarshal([]byte(reply), &response)
           335  	if err != nil {
           336  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", follower.Name, err)
           337  		follower.State = TimeErrorSentUpdate
           338  		return &follower
           339  	}
           340  
           341  	// Registrar la respuesta
           342  	followerName := response["followerName"]
           343  	operation := response["operation"]
           344  	log.Printf("Respuesta de %s: Operación %s exitosa", followerName, operation)
           345  
           346  	follower.State = TimeUpdated
           347  	return &follower
           348  }
           349  func (l *Leader) sendCloseMessagesToFollowers() {
           350  	// Crear un WaitGroup para esperar a que todas las goroutines terminen
           351  	var wg sync.WaitGroup
           352  
           353  	// Canal para recibir los resultados de las goroutines
           354  	resultCh := make(chan string, len(l.TimeUpdatedFollowers))
           355  
           356  	// Enviar mensaje de cierre a cada seguidor de manera concurrente
           357  	for _, follower := range l.TimeUpdatedFollowers {
           358  		wg.Add(1)
           359  		go func(follower FollowerInfo) {
           360  			defer wg.Done()
           361  
           362  			// Enviar el mensaje de cierre
           363  			err := l.sendCloseMessage(follower.Address, follower.Name)
           364  			if err != nil {
           365  				resultCh <- fmt.Sprintf("Error al enviar mensaje de cierre a %s: %s", follower.Name, err)
           366  				return
           367  			}
           368  
           369  			// Simulamos que el mensaje fue enviado exitosamente
           370  			resultCh <- fmt.Sprintf("Mensaje de cierre enviado con éxito a %s", follower.Name)
           371  		}(*follower)
           372  	}
           373  
           374  	// Esperar a que todas las goroutines terminen
           375  	go func() {
           376  		wg.Wait()
           377  		close(resultCh)
           378  	}()
           379  
           380  	// Procesar los resultados a medida que vayan llegando
           381  	for result := range resultCh {
           382  		log.Println(result)
           383  	}
           384  
           385  }
           386  
           387  // SendCloseMessage envía un mensaje de cierre a un seguidor.
           388  // Simulación de la función para enviar mensaje de cierre a un seguidor
           389  func (l *Leader) sendCloseMessage(followerAddress, followerName string) *FollowerInfo {
           390  	log.Printf("Enviando mensaje de cierre a %s...", followerAddress)
           391  
           392  	request := closeRequest{
           393  		Message:    "Cerrar conexión",
           394  		Operation:  "CLOSE",
           395  		LeaderAddr: l.aAbstractNode.Address,
           396  	}
           397  
           398  	// Convertir el mensaje a JSON
           399  	jsonRequest, err := json.Marshal(request)
           400  	if err != nil {
           401  		log.Printf("error al crear mensaje de cierre: %w", err)
           402  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           403  		followError.State = ErrorClose
           404  		return followError
           405  	}
           406  
           407  	// Simulamos el envío del mensaje al seguidor (usando un canal)
           408  	log.Printf("Mensaje de cierre enviado a %s: %s", followerAddress, jsonRequest)
           409  	// Serializar la solicitud a JSON
           410  
           411  	requestString := string(jsonRequest)
           412  	log.Printf("Solicitud enviada a %s: %s", followerAddress, requestString)
           413  	// Enviar la solicitud
           414  	reply, err := l.aAbstractNode.SendMessageSync(followerAddress, requestString)
           415  	if err != nil {
           416  		log.Printf("Error al recibir respuesta de %s: %v", followerAddress, err)
           417  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           418  		followError.State = ErrorClose
           419  		return followError
           420  	}
           421  
           422  	var response map[string]string
           423  	err = json.Unmarshal([]byte(reply), &response)
           424  	if err != nil {
           425  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", followerName, err)
           426  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           427  		followError.State = ErrorClose
           428  		return followError
           429  	}
           430  	// Simulamos una respuesta (en un caso real recibirías la respuesta desde el socket)
           431  	// Aquí se simula un éxito.
           432  	response = map[string]string{
           433  		"followerName": followerAddress,
           434  		"operation":    "CLOSE",
           435  	}
           436  
           437  	// Convertimos la respuesta a JSON
           438  	jsonResponse, err := json.Marshal(response)
           439  	if err != nil {
           440  		log.Printf("error al procesar la respuesta: %w", err)
           441  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           442  		followError.State = ErrorClose
           443  		return followError
           444  	}
           445  
           446  	// Simulamos la recepción de la respuesta (en un caso real, recibirías el mensaje desde el socket)
           447  	log.Printf("Respuesta recibida de %s: %s", followerAddress, jsonResponse)
           448  	follow := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           449  	follow.State = OkClose
           450  	return follow
           451  }
           452  
           453  // PrintResults muestra los resultados del algoritmo.
           454  func (l *Leader) printResults() {
           455  	l.Logger.Println("Resultados del algoritmo Berkeley:")
           456  
           457  	// Mostrar seguidores inalcanzables
           458  	l.Logger.Println("Seguidores inalcanzables:")
           459  	for key, value := range l.UnreachableFollowers {
           460  		l.Logger.Printf("- %s: %v", key, value)
           461  	}
           462  
           463  	// Mostrar seguidores que no respondieron a tiempo
           464  	l.Logger.Println("Seguidores que no respondieron a tiempo:")
           465  	for key, value := range l.NonRespondingFollowers {
           466  		l.Logger.Printf("- %s: %v", key, value)
           467  	}
           468  
           469  	// Mostrar seguidores que respondieron correctamente
           470  	l.Logger.Println("Seguidores que respondieron correctamente:")
           471  	for key, value := range l.SuccessfulFollowers {
           472  		l.Logger.Printf("- %s: %v", key, value)
           473  	}
           474  
           475  	// Mostrar seguidores que actualizaron su tiempo correctamente
           476  	l.Logger.Println("Seguidores que actualizaron su tiempo correctamente:")
           477  	for key, value := range l.TimeUpdatedFollowers {
           478  		l.Logger.Printf("- %s: %v", key, value)
           479  	}
           480  
           481  	// Mostrar seguidores que no pudieron actualizar su tiempo
           482  	l.Logger.Println("Seguidores que no pudieron actualizar su tiempo:")
           483  	for key, value := range l.FailedFollowers {
           484  		l.Logger.Printf("- %s: %v", key, value)
           485  	}
           486  }
           487  func (l *Leader) Close() {
           488  	l.aAbstractNode.Close()
           489  }
           490  
        

        View as plain text

        src/goberkeley/berkeley/logger_manager.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/logger_manager.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"github.com/sirupsen/logrus"
             5  	"reflect"
             6  )
             7  
             8  // LoggerManager es responsable de gestionar los loggers para las clases que lo invocan.
             9  type LoggerManager struct{}
            10  
            11  // GetLogger obtiene el logger correspondiente a la clase que invoca este método.
            12  func (LoggerManager) GetLogger(clazz interface{}) *logrus.Logger {
            13  	// Se usa el nombre de la clase (tipo) como parte del nombre del logger.
            14  	logger := logrus.New()
            15  
            16  	// Se asigna el nombre del tipo (nombre de la clase)
            17  	logger.SetFormatter(&logrus.TextFormatter{
            18  		FullTimestamp: true,
            19  	})
            20  	logger.SetLevel(logrus.InfoLevel)
            21  
            22  	className := reflect.TypeOf(clazz).Name()
            23  	logger.Infof("Logger for %s initialized.", className)
            24  
            25  	return logger
            26  }
            27  
        

        View as plain text

        src/goberkeley/berkeley/socket_zero_mq_exception.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/socket_zero_mq_exception.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  )
             6  
             7  // ErrorType enum para los diferentes tipos de errores posibles en ZeroMQ.
             8  type ErrorType int
             9  
            10  const (
            11  	// CONNECTION_ERROR Error relacionado con la conexión de ZeroMQ
            12  	CONNECTION_ERROR ErrorType = iota
            13  	// SEND_ERROR Error al enviar un mensaje a través del socket
            14  	SEND_ERROR
            15  	// RECEIVE_ERROR Error al recibir un mensaje del socket
            16  	RECEIVE_ERROR
            17  )
            18  
            19  // SocketZeroMQException estructura que encapsula un error personalizado para ZeroMQ.
            20  type SocketZeroMQException struct {
            21  	Message   string    // Mensaje de error
            22  	ErrorType ErrorType // Tipo de error
            23  }
            24  
            25  // NewSocketZeroMQException crea una nueva instancia de SocketZeroMQException.
            26  func NewSocketZeroMQException(message string, errorType ErrorType) *SocketZeroMQException {
            27  	return &SocketZeroMQException{
            28  		Message:   message,
            29  		ErrorType: errorType,
            30  	}
            31  }
            32  
            33  // Error implementación de la interfaz error para SocketZeroMQException.
            34  func (e *SocketZeroMQException) Error() string {
            35  	return fmt.Sprintf("Error: %s, Tipo de error: %v", e.Message, e.ErrorType)
            36  }
            37  
            38  // GetErrorType obtiene el tipo de error.
            39  func (e *SocketZeroMQException) GetErrorType() ErrorType {
            40  	return e.ErrorType
            41  }
            42  
        

        View as plain text

        src/goberkeley/berkeley/anode.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/anode.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"errors"
             5  	"log"
             6  	"time"
             7  
             8  	zmq "github.com/pebbe/zmq4" // Librería para trabajar con ZeroMQ
             9  )
            10  
            11  // Interfaz Handler con el método HandleProcess
            12  type Handler interface {
            13  	HandleProcess(message string) (string, error)
            14  }
            15  
            16  // AbstractNode proporciona la funcionalidad base para nodos en el sistema.
            17  type AbstractNode struct {
            18  	Name          string
            19  	Address       string
            20  	Timeout       time.Duration
            21  	NodeAddresses map[string]string
            22  	Context       *zmq.Context
            23  	Socket        *zmq.Socket
            24  	Logger        *log.Logger
            25  	Handler       // Composición de la interfaz Handler
            26  }
            27  
            28  // NewAbstractNode crea e inicializa un nuevo nodo base.
            29  func NewAbstractNode(name, address string, timeout time.Duration) (*AbstractNode, error) {
            30  	context, err := zmq.NewContext()
            31  	if err != nil {
            32  		return nil, errors.New("error al crear el contexto ZeroMQ")
            33  	}
            34  
            35  	return &AbstractNode{
            36  		Name:    name,
            37  		Address: address,
            38  		Timeout: timeout,
            39  		Context: context,
            40  		Logger:  log.Default(),
            41  	}, nil
            42  }
            43  
            44  // InitializeNodeWithAddresses inicializa un nodo con direcciones de otros nodos.
            45  func InitializeNodeWithAddresses(name, address string, timeout time.Duration, addresses map[string]string) (*AbstractNode, error) {
            46  	var n *AbstractNode
            47  	n, err := NewAbstractNode(name, address, timeout)
            48  	if err != nil {
            49  		return nil, err
            50  	}
            51  	n.NodeAddresses = addresses
            52  	n.Logger.Printf("Nodo %s inicializado con direcciones %v", n.Name, addresses)
            53  	return n, nil
            54  }
            55  
            56  // SendMessageSync envía un mensaje de forma síncrona y espera una respuesta.
            57  func (n *AbstractNode) SendMessageSync(address string, message string) (string, error) {
            58  	// Creación del socket REQ (Request) para enviar el mensaje
            59  	var socket *zmq.Socket
            60  	socket, err := n.Context.NewSocket(zmq.REQ)
            61  	if err != nil {
            62  		n.Logger.Printf("Error al crear el socket REQ: %v", err) // Traza adicional
            63  		return "", errors.New("error al crear el socket REQ")
            64  	}
            65  	defer socket.Close()
            66  
            67  	// Establecer el timeout para recibir respuestas
            68  	socket.SetRcvtimeo(n.Timeout * time.Millisecond) // Convertir el timeout a milisegundos
            69  
            70  	// Traza: Mostrar el valor del timeout configurado
            71  	n.Logger.Printf("Timeout de recepción configurado a: %v milisegundos", int64(n.Timeout)) // Traza para el timeout
            72  
            73  	// Conectar al socket en la dirección proporcionada
            74  	err = socket.Connect("tcp://" + address)
            75  	if err != nil {
            76  		n.Logger.Printf("Error al conectar con %s: %v", address, err) // Traza adicional
            77  		return "", errors.New("error al conectar con " + address)
            78  	}
            79  
            80  	n.Logger.Printf("Conectado a %s", address) // Traza para verificar la conexión
            81  
            82  	// Enviar el mensaje al servidor
            83  	_, err = socket.Send(message, 0)
            84  	if err != nil {
            85  		n.Logger.Printf("Error al enviar el mensaje a %s: %v", address, err) // Traza adicional
            86  		return "", errors.New("error al enviar el mensaje")
            87  	}
            88  
            89  	n.Logger.Printf("Mensaje enviado a %s: %s", address, message) // Traza de envío
            90  
            91  	// Intentar recibir la respuesta
            92  	reply, err := socket.Recv(0)
            93  	if err != nil {
            94  		n.Logger.Printf("Error al recibir respuesta de %s: %v", address, err) // Traza para el error de recepción
            95  		return "", errors.New("no se recibió respuesta del socket")
            96  	}
            97  
            98  	n.Logger.Printf("Respuesta recibida de %s: %s", address, reply) // Traza de respuesta recibida
            99  	return reply, nil
           100  }
           101  
           102  // SendMessageAsync envía un mensaje de manera asíncrona.
           103  func (n *AbstractNode) SendMessageAsync(address, message string) error {
           104  	socket, err := n.Context.NewSocket(zmq.PUSH)
           105  	if err != nil {
           106  		return errors.New("error al crear el socket PUSH")
           107  	}
           108  	defer socket.Close()
           109  
           110  	err = socket.Connect("tcp://" + address)
           111  	if err != nil {
           112  		return errors.New("error al conectar con " + address)
           113  	}
           114  
           115  	_, err = socket.Send(message, 0)
           116  	if err != nil {
           117  		return errors.New("error al enviar el mensaje")
           118  	}
           119  
           120  	n.Logger.Printf("Mensaje asincrónico enviado a %s: %s", address, message)
           121  	return nil
           122  }
           123  
           124  // StartListening inicia el proceso de escucha para mensajes entrantes en el nodo.
           125  // Configura un socket de tipo REP (Response) para recibir y responder a mensajes.
           126  func (n *AbstractNode) StartListening() error {
           127  	// Log para indicar que estamos intentando crear un socket REP.
           128  	n.Logger.Printf("Intentando crear un socket REP para el nodo %s en la dirección %s", n.Name, n.Address)
           129  	socket, err := n.Context.NewSocket(zmq.REP)
           130  	if err != nil {
           131  		// Si ocurre un error al crear el socket, loguea el error y retorna un mensaje de error.
           132  		n.Logger.Printf("Error al crear el socket REP: %v", err)
           133  		return errors.New("error al crear el socket REP")
           134  	}
           135  	n.Socket = socket
           136  	n.Logger.Printf("Socket REP creado exitosamente para el nodo %s", n.Name)
           137  
           138  	// Enlaza el socket a la dirección TCP proporcionada en el nodo para esperar conexiones.
           139  	n.Logger.Printf("Enlazando el socket REP en la dirección tcp://%s", n.Address)
           140  	err = socket.Bind("tcp://" + n.Address)
           141  	if err != nil {
           142  		// Si ocurre un error al enlazar el socket, loguea el error y retorna un mensaje de error.
           143  		n.Logger.Printf("Error al enlazar el socket en %s: %v", n.Address, err)
           144  		return errors.New("error al enlazar el socket en " + n.Address)
           145  	}
           146  	n.Logger.Printf("Socket enlazado exitosamente en %s", n.Address)
           147  
           148  	// Inicia una nueva goroutine para escuchar de manera concurrente sin bloquear el hilo principal.
           149  	n.Logger.Printf("Iniciando goroutine para escuchar en el nodo %s", n.Name)
           150  	go func() {
           151  		// Logea que el nodo ha comenzado a escuchar en la dirección configurada.
           152  		n.Logger.Printf("Nodo %s escuchando en %s", n.Name, n.Address)
           153  
           154  		// Entra en un bucle infinito para recibir y procesar mensajes.
           155  		for {
           156  			// Recibe un mensaje del socket.
           157  			n.Logger.Printf("Esperando mensaje en %s...", n.Name)
           158  			message, err := socket.Recv(0)
           159  			if err != nil {
           160  				// Si ocurre un error al recibir el mensaje, loguea el error y termina el bucle.
           161  				n.Logger.Printf("Error al recibir mensaje: %v", err)
           162  				break
           163  			}
           164  			n.Logger.Printf("Mensaje recibido en %s: %v", n.Name, message)
           165  
           166  			// Llama al método HandleProcess, que es implementado por el tipo real de nodo (Follower, Leader, etc.).
           167  			// Este método procesará el mensaje recibido y generará una respuesta.
           168  			n.Logger.Printf("Procesando mensaje en %s...", n.Name)
           169  			response, err := n.Handler.HandleProcess(message)
           170  			if err != nil {
           171  				// Si hay un error al procesar el mensaje, loguea el error y termina el bucle.
           172  				n.Logger.Printf("Error en HandleProcess en %s: %v", n.Name, err)
           173  				break
           174  			}
           175  
           176  			// Envía la respuesta de vuelta al cliente a través del socket.
           177  			n.Logger.Printf("Enviando respuesta en %s: %v", n.Name, response)
           178  			_, err = socket.Send(response, 0)
           179  			if err != nil {
           180  				// Si ocurre un error al enviar la respuesta, loguea el error y termina el bucle.
           181  				n.Logger.Printf("Error al enviar respuesta en %s: %v", n.Name, err)
           182  				break
           183  			}
           184  		}
           185  	}()
           186  
           187  	// La función regresa nil si todo se configura correctamente y la goroutine se inicia sin errores.
           188  	n.Logger.Printf("Escucha iniciada exitosamente en el nodo %s", n.Name)
           189  	return nil
           190  }
           191  
           192  // Close cierra los recursos del nodo.
           193  func (n *AbstractNode) Close() error {
           194  	if n.Socket != nil {
           195  		n.Socket.Close()
           196  		n.Logger.Printf("Socket cerrado para el nodo %s", n.Name)
           197  	}
           198  	if n.Context != nil {
           199  		n.Context.Term()
           200  		n.Logger.Printf("Contexto cerrado para el nodo %s", n.Name)
           201  	}
           202  	return nil
           203  }
           204  
           205  // handleProcess debe ser sobrescrito por las subclases para procesar mensajes.
           206  func (n *AbstractNode) handleProcess(message string) string {
           207  	n.Logger.Printf("Procesando mensaje: %s", message)
           208  	return `{"status":"unhandled"}`
           209  }
           210  
        

        View as plain text

        builtin - Go Documentation Server
        ...

        Package builtin

        import "builtin"
        Overview
        Index

        Overview ▾

        Package builtin provides documentation for Go's predeclared identifiers. The items documented here are not actually in package builtin but their descriptions here allow godoc to present documentation for the language's special identifiers.

        Constants

        true and false are the two untyped boolean values.

        const (
            true  = 0 == 0 // Untyped bool.
            false = 0 != 0 // Untyped bool.
        )

        iota is a predeclared identifier representing the untyped integer ordinal number of the current const specification in a (usually parenthesized) const declaration. It is zero-indexed.

        const iota = 0 // Untyped int.
        

        Variables

        nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.

        var nil Type // Type must be a pointer, channel, func, interface, map, or slice type
        

        func append

        func append(slice []Type, elems ...Type) []Type

        The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:

        slice = append(slice, elem1, elem2)
        slice = append(slice, anotherSlice...)
        

        As a special case, it is legal to append a string to a byte slice, like this:

        slice = append([]byte("hello "), "world"...)
        

        func cap

        func cap(v Type) int

        The cap built-in function returns the capacity of v, according to its type:

        Array: the number of elements in v (same as len(v)).
        Pointer to array: the number of elements in *v (same as len(v)).
        Slice: the maximum length the slice can reach when resliced;
        if v is nil, cap(v) is zero.
        Channel: the channel buffer capacity, in units of elements;
        if v is nil, cap(v) is zero.
        

        For some arguments, such as a simple array expression, the result can be a constant. See the Go language specification's "Length and capacity" section for details.

        func clear

        func clear[T ~[]Type | ~map[Type]Type1](t T)

        The clear built-in function clears maps and slices. For maps, clear deletes all entries, resulting in an empty map. For slices, clear sets all elements up to the length of the slice to the zero value of the respective element type. If the argument type is a type parameter, the type parameter's type set must contain only map or slice types, and clear performs the operation implied by the type argument.

        func close

        func close(c chan<- Type)

        The close built-in function closes a channel, which must be either bidirectional or send-only. It should be executed only by the sender, never the receiver, and has the effect of shutting down the channel after the last sent value is received. After the last value has been received from a closed channel c, any receive from c will succeed without blocking, returning the zero value for the channel element. The form

        x, ok := <-c
        

        will also set ok to false for a closed and empty channel.

        func complex

        func complex(r, i FloatType) ComplexType

        The complex built-in function constructs a complex value from two floating-point values. The real and imaginary parts must be of the same size, either float32 or float64 (or assignable to them), and the return value will be the corresponding complex type (complex64 for float32, complex128 for float64).

        func copy

        func copy(dst, src []Type) int

        The copy built-in function copies elements from a source slice into a destination slice. (As a special case, it also will copy bytes from a string to a slice of bytes.) The source and destination may overlap. Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

        func delete

        func delete(m map[Type]Type1, key Type)

        The delete built-in function deletes the element with the specified key (m[key]) from the map. If m is nil or there is no such element, delete is a no-op.

        func imag

        func imag(c ComplexType) FloatType

        The imag built-in function returns the imaginary part of the complex number c. The return value will be floating point type corresponding to the type of c.

        func len

        func len(v Type) int

        The len built-in function returns the length of v, according to its type:

        Array: the number of elements in v.
        Pointer to array: the number of elements in *v (even if v is nil).
        Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
        String: the number of bytes in v.
        Channel: the number of elements queued (unread) in the channel buffer;
                 if v is nil, len(v) is zero.
        

        For some arguments, such as a string literal or a simple array expression, the result can be a constant. See the Go language specification's "Length and capacity" section for details.

        func make

        func make(t Type, size ...IntegerType) Type

        The make built-in function allocates and initializes an object of type slice, map, or chan (only). Like new, the first argument is a type, not a value. Unlike new, make's return type is the same as the type of its argument, not a pointer to it. The specification of the result depends on the type:

        Slice: The size specifies the length. The capacity of the slice is
        equal to its length. A second integer argument may be provided to
        specify a different capacity; it must be no smaller than the
        length. For example, make([]int, 0, 10) allocates an underlying array
        of size 10 and returns a slice of length 0 and capacity 10 that is
        backed by this underlying array.
        Map: An empty map is allocated with enough space to hold the
        specified number of elements. The size may be omitted, in which case
        a small starting size is allocated.
        Channel: The channel's buffer is initialized with the specified
        buffer capacity. If zero, or the size is omitted, the channel is
        unbuffered.
        

        func max

        func max[T cmp.Ordered](x T, y ...T) T

        The max built-in function returns the largest value of a fixed number of arguments of cmp.Ordered types. There must be at least one argument. If T is a floating-point type and any of the arguments are NaNs, max will return NaN.

        func min

        func min[T cmp.Ordered](x T, y ...T) T

        The min built-in function returns the smallest value of a fixed number of arguments of cmp.Ordered types. There must be at least one argument. If T is a floating-point type and any of the arguments are NaNs, min will return NaN.

        func new

        func new(Type) *Type

        The new built-in function allocates memory. The first argument is a type, not a value, and the value returned is a pointer to a newly allocated zero value of that type.

        func panic

        func panic(v any)

        The panic built-in function stops normal execution of the current goroutine. When a function F calls panic, normal execution of F stops immediately. Any functions whose execution was deferred by F are run in the usual way, and then F returns to its caller. To the caller G, the invocation of F then behaves like a call to panic, terminating G's execution and running any deferred functions. This continues until all functions in the executing goroutine have stopped, in reverse order. At that point, the program is terminated with a non-zero exit code. This termination sequence is called panicking and can be controlled by the built-in function recover.

        Starting in Go 1.21, calling panic with a nil interface value or an untyped nil causes a run-time error (a different panic). The GODEBUG setting panicnil=1 disables the run-time error.

        func print

        func print(args ...Type)

        The print built-in function formats its arguments in an implementation-specific way and writes the result to standard error. Print is useful for bootstrapping and debugging; it is not guaranteed to stay in the language.

        func println

        func println(args ...Type)

        The println built-in function formats its arguments in an implementation-specific way and writes the result to standard error. Spaces are always added between arguments and a newline is appended. Println is useful for bootstrapping and debugging; it is not guaranteed to stay in the language.

        func real

        func real(c ComplexType) FloatType

        The real built-in function returns the real part of the complex number c. The return value will be floating point type corresponding to the type of c.

        func recover

        func recover() any

        The recover built-in function allows a program to manage behavior of a panicking goroutine. Executing a call to recover inside a deferred function (but not any function called by it) stops the panicking sequence by restoring normal execution and retrieves the error value passed to the call of panic. If recover is called outside the deferred function it will not stop a panicking sequence. In this case, or when the goroutine is not panicking, recover returns nil.

        Prior to Go 1.21, recover would also return nil if panic is called with a nil argument. See [panic] for details.

        type ComplexType

        ComplexType is here for the purposes of documentation only. It is a stand-in for either complex type: complex64 or complex128.

        type ComplexType complex64

        type FloatType

        FloatType is here for the purposes of documentation only. It is a stand-in for either float type: float32 or float64.

        type FloatType float32

        type IntegerType

        IntegerType is here for the purposes of documentation only. It is a stand-in for any integer type: int, uint, int8 etc.

        type IntegerType int

        type Type

        Type is here for the purposes of documentation only. It is a stand-in for any Go type, but represents the same type for any given function invocation.

        type Type int

        type Type1

        Type1 is here for the purposes of documentation only. It is a stand-in for any Go type, but represents the same type for any given function invocation.

        type Type1 int

        type any

        any is an alias for interface{} and is equivalent to interface{} in all ways.

        type any = interface{}

        type bool

        bool is the set of boolean values, true and false.

        type bool bool

        type byte

        byte is an alias for uint8 and is equivalent to uint8 in all ways. It is used, by convention, to distinguish byte values from 8-bit unsigned integer values.

        type byte = uint8

        type comparable

        comparable is an interface that is implemented by all comparable types (booleans, numbers, strings, pointers, channels, arrays of comparable types, structs whose fields are all comparable types). The comparable interface may only be used as a type parameter constraint, not as the type of a variable.

        type comparable interface{ comparable }

        type complex128

        complex128 is the set of all complex numbers with float64 real and imaginary parts.

        type complex128 complex128

        type complex64

        complex64 is the set of all complex numbers with float32 real and imaginary parts.

        type complex64 complex64

        type error

        The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error.

        type error interface {
            Error() string
        }

        type float32

        float32 is the set of all IEEE-754 32-bit floating-point numbers.

        type float32 float32

        type float64

        float64 is the set of all IEEE-754 64-bit floating-point numbers.

        type float64 float64

        type int

        int is a signed integer type that is at least 32 bits in size. It is a distinct type, however, and not an alias for, say, int32.

        type int int

        type int16

        int16 is the set of all signed 16-bit integers. Range: -32768 through 32767.

        type int16 int16

        type int32

        int32 is the set of all signed 32-bit integers. Range: -2147483648 through 2147483647.

        type int32 int32

        type int64

        int64 is the set of all signed 64-bit integers. Range: -9223372036854775808 through 9223372036854775807.

        type int64 int64

        type int8

        int8 is the set of all signed 8-bit integers. Range: -128 through 127.

        type int8 int8

        type rune

        rune is an alias for int32 and is equivalent to int32 in all ways. It is used, by convention, to distinguish character values from integer values.

        type rune = int32

        type string

        string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. A string may be empty, but not nil. Values of string type are immutable.

        type string string

        type uint

        uint is an unsigned integer type that is at least 32 bits in size. It is a distinct type, however, and not an alias for, say, uint32.

        type uint uint

        type uint16

        uint16 is the set of all unsigned 16-bit integers. Range: 0 through 65535.

        type uint16 uint16

        type uint32

        uint32 is the set of all unsigned 32-bit integers. Range: 0 through 4294967295.

        type uint32 uint32

        type uint64

        uint64 is the set of all unsigned 64-bit integers. Range: 0 through 18446744073709551615.

        type uint64 uint64

        type uint8

        uint8 is the set of all unsigned 8-bit integers. Range: 0 through 255.

        type uint8 uint8

        type uintptr

        uintptr is an integer type that is large enough to hold the bit pattern of any pointer.

        type uintptr uintptr
        time - Go Documentation Server
        ...

        Package time

        Overview ▾

        Package time provides functionality for measuring and displaying time.

        The calendrical calculations always assume a Gregorian calendar, with no leap seconds.

        Monotonic Clocks

        Operating systems provide both a “wall clock,” which is subject to changes for clock synchronization, and a “monotonic clock,” which is not. The general rule is that the wall clock is for telling time and the monotonic clock is for measuring time. Rather than split the API, in this package the Time returned by time.Now contains both a wall clock reading and a monotonic clock reading; later time-telling operations use the wall clock reading, but later time-measuring operations, specifically comparisons and subtractions, use the monotonic clock reading.

        For example, this code always computes a positive elapsed time of approximately 20 milliseconds, even if the wall clock is changed during the operation being timed:

        start := time.Now()
        ... operation that takes 20 milliseconds ...
        t := time.Now()
        elapsed := t.Sub(start)
        

        Other idioms, such as time.Since(start), time.Until(deadline), and time.Now().Before(deadline), are similarly robust against wall clock resets.

        The rest of this section gives the precise details of how operations use monotonic clocks, but understanding those details is not required to use this package.

        The Time returned by time.Now contains a monotonic clock reading. If Time t has a monotonic clock reading, t.Add adds the same duration to both the wall clock and monotonic clock readings to compute the result. Because t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time computations, they always strip any monotonic clock reading from their results. Because t.In, t.Local, and t.UTC are used for their effect on the interpretation of the wall time, they also strip any monotonic clock reading from their results. The canonical way to strip a monotonic clock reading is to use t = t.Round(0).

        If Times t and u both contain monotonic clock readings, the operations t.After(u), t.Before(u), t.Equal(u), t.Compare(u), and t.Sub(u) are carried out using the monotonic clock readings alone, ignoring the wall clock readings. If either t or u contains no monotonic clock reading, these operations fall back to using the wall clock readings.

        On some systems the monotonic clock will stop if the computer goes to sleep. On such a system, t.Sub(u) may not accurately reflect the actual time that passed between t and u.

        Because the monotonic clock reading has no meaning outside the current process, the serialized forms generated by t.GobEncode, t.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic clock reading, and t.Format provides no format for it. Similarly, the constructors time.Date, time.Parse, time.ParseInLocation, and time.Unix, as well as the unmarshalers t.GobDecode, t.UnmarshalBinary. t.UnmarshalJSON, and t.UnmarshalText always create times with no monotonic clock reading.

        The monotonic clock reading exists only in Time values. It is not a part of Duration values or the Unix times returned by t.Unix and friends.

        Note that the Go == operator compares not just the time instant but also the Location and the monotonic clock reading. See the documentation for the Time type for a discussion of equality testing for Time values.

        For debugging, the result of t.String does include the monotonic clock reading if present. If t != u because of different monotonic clock readings, that difference will be visible when printing t.String() and u.String().

        Timer Resolution

        Timer resolution varies depending on the Go runtime, the operating system and the underlying hardware. On Unix, the resolution is approximately 1ms. On Windows, the default resolution is approximately 16ms, but a higher resolution may be requested using golang.org/x/sys/windows.TimeBeginPeriod.

        Index ▾

        Constants
        func After(d Duration) <-chan Time
        func Sleep(d Duration)
        func Tick(d Duration) <-chan Time
        type Duration
            func ParseDuration(s string) (Duration, error)
            func Since(t Time) Duration
            func Until(t Time) Duration
            func (d Duration) Abs() Duration
            func (d Duration) Hours() float64
            func (d Duration) Microseconds() int64
            func (d Duration) Milliseconds() int64
            func (d Duration) Minutes() float64
            func (d Duration) Nanoseconds() int64
            func (d Duration) Round(m Duration) Duration
            func (d Duration) Seconds() float64
            func (d Duration) String() string
            func (d Duration) Truncate(m Duration) Duration
        type Location
            func FixedZone(name string, offset int) *Location
            func LoadLocation(name string) (*Location, error)
            func LoadLocationFromTZData(name string, data []byte) (*Location, error)
            func (l *Location) String() string
        type Month
            func (m Month) String() string
        type ParseError
            func (e *ParseError) Error() string
        type Ticker
            func NewTicker(d Duration) *Ticker
            func (t *Ticker) Reset(d Duration)
            func (t *Ticker) Stop()
        type Time
            func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
            func Now() Time
            func Parse(layout, value string) (Time, error)
            func ParseInLocation(layout, value string, loc *Location) (Time, error)
            func Unix(sec int64, nsec int64) Time
            func UnixMicro(usec int64) Time
            func UnixMilli(msec int64) Time
            func (t Time) Add(d Duration) Time
            func (t Time) AddDate(years int, months int, days int) Time
            func (t Time) After(u Time) bool
            func (t Time) AppendFormat(b []byte, layout string) []byte
            func (t Time) Before(u Time) bool
            func (t Time) Clock() (hour, min, sec int)
            func (t Time) Compare(u Time) int
            func (t Time) Date() (year int, month Month, day int)
            func (t Time) Day() int
            func (t Time) Equal(u Time) bool
            func (t Time) Format(layout string) string
            func (t Time) GoString() string
            func (t *Time) GobDecode(data []byte) error
            func (t Time) GobEncode() ([]byte, error)
            func (t Time) Hour() int
            func (t Time) ISOWeek() (year, week int)
            func (t Time) In(loc *Location) Time
            func (t Time) IsDST() bool
            func (t Time) IsZero() bool
            func (t Time) Local() Time
            func (t Time) Location() *Location
            func (t Time) MarshalBinary() ([]byte, error)
            func (t Time) MarshalJSON() ([]byte, error)
            func (t Time) MarshalText() ([]byte, error)
            func (t Time) Minute() int
            func (t Time) Month() Month
            func (t Time) Nanosecond() int
            func (t Time) Round(d Duration) Time
            func (t Time) Second() int
            func (t Time) String() string
            func (t Time) Sub(u Time) Duration
            func (t Time) Truncate(d Duration) Time
            func (t Time) UTC() Time
            func (t Time) Unix() int64
            func (t Time) UnixMicro() int64
            func (t Time) UnixMilli() int64
            func (t Time) UnixNano() int64
            func (t *Time) UnmarshalBinary(data []byte) error
            func (t *Time) UnmarshalJSON(data []byte) error
            func (t *Time) UnmarshalText(data []byte) error
            func (t Time) Weekday() Weekday
            func (t Time) Year() int
            func (t Time) YearDay() int
            func (t Time) Zone() (name string, offset int)
            func (t Time) ZoneBounds() (start, end Time)
        type Timer
            func AfterFunc(d Duration, f func()) *Timer
            func NewTimer(d Duration) *Timer
            func (t *Timer) Reset(d Duration) bool
            func (t *Timer) Stop() bool
        type Weekday
            func (d Weekday) String() string

        Package files

        format.go format_rfc3339.go sleep.go sys_unix.go tick.go time.go zoneinfo.go zoneinfo_goroot.go zoneinfo_read.go zoneinfo_unix.go

        Constants

        These are predefined layouts for use in Time.Format and time.Parse. The reference time used in these layouts is the specific time stamp:

        01/02 03:04:05PM '06 -0700
        

        (January 2, 15:04:05, 2006, in time zone seven hours west of GMT). That value is recorded as the constant named Layout, listed below. As a Unix time, this is 1136239445. Since MST is GMT-0700, the reference would be printed by the Unix date command as:

        Mon Jan 2 15:04:05 MST 2006
        

        It is a regrettable historic error that the date uses the American convention of putting the numerical month before the day.

        The example for Time.Format demonstrates the working of the layout string in detail and is a good reference.

        Note that the RFC822, RFC850, and RFC1123 formats should be applied only to local times. Applying them to UTC times will use "UTC" as the time zone abbreviation, while strictly speaking those RFCs require the use of "GMT" in that case. In general RFC1123Z should be used instead of RFC1123 for servers that insist on that format, and RFC3339 should be preferred for new protocols. RFC3339, RFC822, RFC822Z, RFC1123, and RFC1123Z are useful for formatting; when used with time.Parse they do not accept all the time formats permitted by the RFCs and they do accept time formats not formally defined. The RFC3339Nano format removes trailing zeros from the seconds field and thus may not sort correctly once formatted.

        Most programs can use one of the defined constants as the layout passed to Format or Parse. The rest of this comment can be ignored unless you are creating a custom layout string.

        To define your own format, write down what the reference time would look like formatted your way; see the values of constants like ANSIC, StampMicro or Kitchen for examples. The model is to demonstrate what the reference time looks like so that the Format and Parse methods can apply the same transformation to a general time value.

        Here is a summary of the components of a layout string. Each element shows by example the formatting of an element of the reference time. Only these values are recognized. Text in the layout string that is not recognized as part of the reference time is echoed verbatim during Format and expected to appear verbatim in the input to Parse.

        Year: "2006" "06"
        Month: "Jan" "January" "01" "1"
        Day of the week: "Mon" "Monday"
        Day of the month: "2" "_2" "02"
        Day of the year: "__2" "002"
        Hour: "15" "3" "03" (PM or AM)
        Minute: "4" "04"
        Second: "5" "05"
        AM/PM mark: "PM"
        

        Numeric time zone offsets format as follows:

        "-0700"     ±hhmm
        "-07:00"    ±hh:mm
        "-07"       ±hh
        "-070000"   ±hhmmss
        "-07:00:00" ±hh:mm:ss
        

        Replacing the sign in the format with a Z triggers the ISO 8601 behavior of printing Z instead of an offset for the UTC zone. Thus:

        "Z0700"      Z or ±hhmm
        "Z07:00"     Z or ±hh:mm
        "Z07"        Z or ±hh
        "Z070000"    Z or ±hhmmss
        "Z07:00:00"  Z or ±hh:mm:ss
        

        Within the format string, the underscores in "_2" and "__2" represent spaces that may be replaced by digits if the following number has multiple digits, for compatibility with fixed-width Unix time formats. A leading zero represents a zero-padded value.

        The formats __2 and 002 are space-padded and zero-padded three-character day of year; there is no unpadded day of year format.

        A comma or decimal point followed by one or more zeros represents a fractional second, printed to the given number of decimal places. A comma or decimal point followed by one or more nines represents a fractional second, printed to the given number of decimal places, with trailing zeros removed. For example "15:04:05,000" or "15:04:05.000" formats or parses with millisecond precision.

        Some valid layouts are invalid time values for time.Parse, due to formats such as _ for space padding and Z for zone information.

        const (
            Layout      = "01/02 03:04:05PM '06 -0700" // The reference time, in numerical order.
            ANSIC       = "Mon Jan _2 15:04:05 2006"
            UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
            RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
            RFC822      = "02 Jan 06 15:04 MST"
            RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
            RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
            RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
            RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
            RFC3339     = "2006-01-02T15:04:05Z07:00"
            RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
            Kitchen     = "3:04PM"
            // Handy time stamps.
            Stamp      = "Jan _2 15:04:05"
            StampMilli = "Jan _2 15:04:05.000"
            StampMicro = "Jan _2 15:04:05.000000"
            StampNano  = "Jan _2 15:04:05.000000000"
            DateTime   = "2006-01-02 15:04:05"
            DateOnly   = "2006-01-02"
            TimeOnly   = "15:04:05"
        )

        Common durations. There is no definition for units of Day or larger to avoid confusion across daylight savings time zone transitions.

        To count the number of units in a Duration, divide:

        second := time.Second
        fmt.Print(int64(second/time.Millisecond)) // prints 1000
        

        To convert an integer number of units to a Duration, multiply:

        seconds := 10
        fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
        
        const (
            Nanosecond  Duration = 1
            Microsecond          = 1000 * Nanosecond
            Millisecond          = 1000 * Microsecond
            Second               = 1000 * Millisecond
            Minute               = 60 * Second
            Hour                 = 60 * Minute
        )

        func After

        func After(d Duration) <-chan Time

        After waits for the duration to elapse and then sends the current time on the returned channel. It is equivalent to NewTimer(d).C. The underlying Timer is not recovered by the garbage collector until the timer fires. If efficiency is a concern, use NewTimer instead and call Timer.Stop if the timer is no longer needed.

        Example

        Code:

        select {
        case m := <-c:
            handle(m)
        case <-time.After(10 * time.Second):
            fmt.Println("timed out")
        }
        

        func Sleep

        func Sleep(d Duration)

        Sleep pauses the current goroutine for at least the duration d. A negative or zero duration causes Sleep to return immediately.

        Example

        Code:

        time.Sleep(100 * time.Millisecond)
        

        func Tick

        func Tick(d Duration) <-chan Time

        Tick is a convenience wrapper for NewTicker providing access to the ticking channel only. While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks". Unlike NewTicker, Tick will return nil if d <= 0.

        Example

        Code:

        c := time.Tick(5 * time.Second)
        for next := range c {
            fmt.Printf("%v %s\n", next, statusUpdate())
        }
        

        type Duration

        A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years.

        type Duration int64

        Example

        Code:

        t0 := time.Now()
        expensiveCall()
        t1 := time.Now()
        fmt.Printf("The call took %v to run.\n", t1.Sub(t0))
        

        func ParseDuration

        func ParseDuration(s string) (Duration, error)

        ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

        Example

        Code:

        hours, _ := time.ParseDuration("10h")
        complex, _ := time.ParseDuration("1h10m10s")
        micro, _ := time.ParseDuration("1µs")
        // The package also accepts the incorrect but common prefix u for micro.
        micro2, _ := time.ParseDuration("1us")
        
        fmt.Println(hours)
        fmt.Println(complex)
        fmt.Printf("There are %.0f seconds in %v.\n", complex.Seconds(), complex)
        fmt.Printf("There are %d nanoseconds in %v.\n", micro.Nanoseconds(), micro)
        fmt.Printf("There are %6.2e seconds in %v.\n", micro2.Seconds(), micro)
        

        Output:

        10h0m0s
        1h10m10s
        There are 4210 seconds in 1h10m10s.
        There are 1000 nanoseconds in 1µs.
        There are 1.00e-06 seconds in 1µs.
        

        func Since

        func Since(t Time) Duration

        Since returns the time elapsed since t. It is shorthand for time.Now().Sub(t).

        func Until

        func Until(t Time) Duration

        Until returns the duration until t. It is shorthand for t.Sub(time.Now()).

        func (Duration) Abs

        func (d Duration) Abs() Duration

        Abs returns the absolute value of d. As a special case, math.MinInt64 is converted to math.MaxInt64.

        func (Duration) Hours

        func (d Duration) Hours() float64

        Hours returns the duration as a floating point number of hours.

        Example

        Code:

        h, _ := time.ParseDuration("4h30m")
        fmt.Printf("I've got %.1f hours of work left.", h.Hours())
        

        Output:

        I've got 4.5 hours of work left.
        

        func (Duration) Microseconds

        func (d Duration) Microseconds() int64

        Microseconds returns the duration as an integer microsecond count.

        Example

        Code:

        u, _ := time.ParseDuration("1s")
        fmt.Printf("One second is %d microseconds.\n", u.Microseconds())
        

        Output:

        One second is 1000000 microseconds.
        

        func (Duration) Milliseconds

        func (d Duration) Milliseconds() int64

        Milliseconds returns the duration as an integer millisecond count.

        Example

        Code:

        u, _ := time.ParseDuration("1s")
        fmt.Printf("One second is %d milliseconds.\n", u.Milliseconds())
        

        Output:

        One second is 1000 milliseconds.
        

        func (Duration) Minutes

        func (d Duration) Minutes() float64

        Minutes returns the duration as a floating point number of minutes.

        Example

        Code:

        m, _ := time.ParseDuration("1h30m")
        fmt.Printf("The movie is %.0f minutes long.", m.Minutes())
        

        Output:

        The movie is 90 minutes long.
        

        func (Duration) Nanoseconds

        func (d Duration) Nanoseconds() int64

        Nanoseconds returns the duration as an integer nanosecond count.

        Example

        Code:

        u, _ := time.ParseDuration("1µs")
        fmt.Printf("One microsecond is %d nanoseconds.\n", u.Nanoseconds())
        

        Output:

        One microsecond is 1000 nanoseconds.
        

        func (Duration) Round

        func (d Duration) Round(m Duration) Duration

        Round returns the result of rounding d to the nearest multiple of m. The rounding behavior for halfway values is to round away from zero. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, Round returns the maximum (or minimum) duration. If m <= 0, Round returns d unchanged.

        Example

        Code:

        d, err := time.ParseDuration("1h15m30.918273645s")
        if err != nil {
            panic(err)
        }
        
        round := []time.Duration{
            time.Nanosecond,
            time.Microsecond,
            time.Millisecond,
            time.Second,
            2 * time.Second,
            time.Minute,
            10 * time.Minute,
            time.Hour,
        }
        
        for _, r := range round {
            fmt.Printf("d.Round(%6s) = %s\n", r, d.Round(r).String())
        }
        

        Output:

        d.Round(   1ns) = 1h15m30.918273645s
        d.Round(   1µs) = 1h15m30.918274s
        d.Round(   1ms) = 1h15m30.918s
        d.Round(    1s) = 1h15m31s
        d.Round(    2s) = 1h15m30s
        d.Round(  1m0s) = 1h16m0s
        d.Round( 10m0s) = 1h20m0s
        d.Round(1h0m0s) = 1h0m0s
        

        func (Duration) Seconds

        func (d Duration) Seconds() float64

        Seconds returns the duration as a floating point number of seconds.

        Example

        Code:

        m, _ := time.ParseDuration("1m30s")
        fmt.Printf("Take off in t-%.0f seconds.", m.Seconds())
        

        Output:

        Take off in t-90 seconds.
        

        func (Duration) String

        func (d Duration) String() string

        String returns a string representing the duration in the form "72h3m0.5s". Leading zero units are omitted. As a special case, durations less than one second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure that the leading digit is non-zero. The zero duration formats as 0s.

        Example

        Code:

        fmt.Println(1*time.Hour + 2*time.Minute + 300*time.Millisecond)
        fmt.Println(300 * time.Millisecond)
        

        Output:

        1h2m0.3s
        300ms
        

        func (Duration) Truncate

        func (d Duration) Truncate(m Duration) Duration

        Truncate returns the result of rounding d toward zero to a multiple of m. If m <= 0, Truncate returns d unchanged.

        Example

        Code:

        d, err := time.ParseDuration("1h15m30.918273645s")
        if err != nil {
            panic(err)
        }
        
        trunc := []time.Duration{
            time.Nanosecond,
            time.Microsecond,
            time.Millisecond,
            time.Second,
            2 * time.Second,
            time.Minute,
            10 * time.Minute,
            time.Hour,
        }
        
        for _, t := range trunc {
            fmt.Printf("d.Truncate(%6s) = %s\n", t, d.Truncate(t).String())
        }
        

        Output:

        d.Truncate(   1ns) = 1h15m30.918273645s
        d.Truncate(   1µs) = 1h15m30.918273s
        d.Truncate(   1ms) = 1h15m30.918s
        d.Truncate(    1s) = 1h15m30s
        d.Truncate(    2s) = 1h15m30s
        d.Truncate(  1m0s) = 1h15m0s
        d.Truncate( 10m0s) = 1h10m0s
        d.Truncate(1h0m0s) = 1h0m0s
        

        type Location

        A Location maps time instants to the zone in use at that time. Typically, the Location represents the collection of time offsets in use in a geographical area. For many Locations the time offset varies depending on whether daylight savings time is in use at the time instant.

        Location is used to provide a time zone in a printed Time value and for calculations involving intervals that may cross daylight savings time boundaries.

        type Location struct {
            // contains filtered or unexported fields
        }
        

        Local represents the system's local time zone. On Unix systems, Local consults the TZ environment variable to find the time zone to use. No TZ means use the system default /etc/localtime. TZ="" means use UTC. TZ="foo" means use file foo in the system timezone directory.

        var Local *Location = &localLoc

        UTC represents Universal Coordinated Time (UTC).

        var UTC *Location = &utcLoc

        Example

        Code:

        // China doesn't have daylight saving. It uses a fixed 8 hour offset from UTC.
        secondsEastOfUTC := int((8 * time.Hour).Seconds())
        beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
        
        // If the system has a timezone database present, it's possible to load a location
        // from that, e.g.:
        //    newYork, err := time.LoadLocation("America/New_York")
        
        // Creating a time requires a location. Common locations are time.Local and time.UTC.
        timeInUTC := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
        sameTimeInBeijing := time.Date(2009, 1, 1, 20, 0, 0, 0, beijing)
        
        // Although the UTC clock time is 1200 and the Beijing clock time is 2000, Beijing is
        // 8 hours ahead so the two dates actually represent the same instant.
        timesAreEqual := timeInUTC.Equal(sameTimeInBeijing)
        fmt.Println(timesAreEqual)
        
        

        Output:

        true
        

        func FixedZone

        func FixedZone(name string, offset int) *Location

        FixedZone returns a Location that always uses the given zone name and offset (seconds east of UTC).

        Example

        Code:

        loc := time.FixedZone("UTC-8", -8*60*60)
        t := time.Date(2009, time.November, 10, 23, 0, 0, 0, loc)
        fmt.Println("The time is:", t.Format(time.RFC822))
        

        Output:

        The time is: 10 Nov 09 23:00 UTC-8
        

        func LoadLocation

        func LoadLocation(name string) (*Location, error)

        LoadLocation returns the Location with the given name.

        If the name is "" or "UTC", LoadLocation returns UTC. If the name is "Local", LoadLocation returns Local.

        Otherwise, the name is taken to be a location name corresponding to a file in the IANA Time Zone database, such as "America/New_York".

        LoadLocation looks for the IANA Time Zone database in the following locations in order:

        • the directory or uncompressed zip file named by the ZONEINFO environment variable
        • on a Unix system, the system standard installation location
        • $GOROOT/lib/time/zoneinfo.zip
        • the time/tzdata package, if it was imported

        Example

        Code:

        location, err := time.LoadLocation("America/Los_Angeles")
        if err != nil {
            panic(err)
        }
        
        timeInUTC := time.Date(2018, 8, 30, 12, 0, 0, 0, time.UTC)
        fmt.Println(timeInUTC.In(location))
        

        Output:

        2018-08-30 05:00:00 -0700 PDT
        

        func LoadLocationFromTZData

        func LoadLocationFromTZData(name string, data []byte) (*Location, error)

        LoadLocationFromTZData returns a Location with the given name initialized from the IANA Time Zone database-formatted data. The data should be in the format of a standard IANA time zone file (for example, the content of /etc/localtime on Unix systems).

        func (*Location) String

        func (l *Location) String() string

        String returns a descriptive name for the time zone information, corresponding to the name argument to LoadLocation or FixedZone.

        type Month

        A Month specifies a month of the year (January = 1, ...).

        type Month int
        const (
            January Month = 1 + iota
            February
            March
            April
            May
            June
            July
            August
            September
            October
            November
            December
        )

        Example

        Code:

        _, month, day := time.Now().Date()
        if month == time.November && day == 10 {
            fmt.Println("Happy Go day!")
        }
        

        func (Month) String

        func (m Month) String() string

        String returns the English name of the month ("January", "February", ...).

        type ParseError

        ParseError describes a problem parsing a time string.

        type ParseError struct {
            Layout     string
            Value      string
            LayoutElem string
            ValueElem  string
            Message    string
        }
        

        func (*ParseError) Error

        func (e *ParseError) Error() string

        Error returns the string representation of a ParseError.

        type Ticker

        A Ticker holds a channel that delivers “ticks” of a clock at intervals.

        type Ticker struct {
            C <-chan Time // The channel on which the ticks are delivered.
            // contains filtered or unexported fields
        }
        

        func NewTicker

        func NewTicker(d Duration) *Ticker

        NewTicker returns a new Ticker containing a channel that will send the current time on the channel after each tick. The period of the ticks is specified by the duration argument. The ticker will adjust the time interval or drop ticks to make up for slow receivers. The duration d must be greater than zero; if not, NewTicker will panic. Stop the ticker to release associated resources.

        Example

        Code:

        ticker := time.NewTicker(time.Second)
        defer ticker.Stop()
        done := make(chan bool)
        go func() {
            time.Sleep(10 * time.Second)
            done <- true
        }()
        for {
            select {
            case <-done:
                fmt.Println("Done!")
                return
            case t := <-ticker.C:
                fmt.Println("Current time: ", t)
            }
        }
        

        func (*Ticker) Reset

        func (t *Ticker) Reset(d Duration)

        Reset stops a ticker and resets its period to the specified duration. The next tick will arrive after the new period elapses. The duration d must be greater than zero; if not, Reset will panic.

        func (*Ticker) Stop

        func (t *Ticker) Stop()

        Stop turns off a ticker. After Stop, no more ticks will be sent. Stop does not close the channel, to prevent a concurrent goroutine reading from the channel from seeing an erroneous "tick".

        type Time

        A Time represents an instant in time with nanosecond precision.

        Programs using times should typically store and pass them as values, not pointers. That is, time variables and struct fields should be of type time.Time, not *time.Time.

        A Time value can be used by multiple goroutines simultaneously except that the methods GobDecode, UnmarshalBinary, UnmarshalJSON and UnmarshalText are not concurrency-safe.

        Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.

        The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. As this time is unlikely to come up in practice, the IsZero method gives a simple way of detecting a time that has not been initialized explicitly.

        Each time has an associated Location. The methods Local, UTC, and In return a Time with a specific Location. Changing the Location of a Time value with these methods does not change the actual instant it represents, only the time zone in which to interpret it.

        Representations of a Time value saved by the GobEncode, MarshalBinary, MarshalJSON, and MarshalText methods store the Time.Location's offset, but not the location name. They therefore lose information about Daylight Saving Time.

        In addition to the required “wall clock” reading, a Time may contain an optional reading of the current process's monotonic clock, to provide additional precision for comparison or subtraction. See the “Monotonic Clocks” section in the package documentation for details.

        Note that the Go == operator compares not just the time instant but also the Location and the monotonic clock reading. Therefore, Time values should not be used as map or database keys without first guaranteeing that the identical Location has been set for all values, which can be achieved through use of the UTC or Local method, and that the monotonic clock reading has been stripped by setting t = t.Round(0). In general, prefer t.Equal(u) to t == u, since t.Equal uses the most accurate comparison available and correctly handles the case when only one of its arguments has a monotonic clock reading.

        type Time struct {
            // contains filtered or unexported fields
        }
        

        func Date

        func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

        Date returns the Time corresponding to

        yyyy-mm-dd hh:mm:ss + nsec nanoseconds
        

        in the appropriate zone for that time in the given location.

        The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.

        A daylight savings time transition skips or repeats times. For example, in the United States, March 13, 2011 2:15am never occurred, while November 6, 2011 1:15am occurred twice. In such cases, the choice of time zone, and therefore the time, is not well-defined. Date returns a time that is correct in one of the two zones involved in the transition, but it does not guarantee which.

        Date panics if loc is nil.

        Example

        Code:

        t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
        fmt.Printf("Go launched at %s\n", t.Local())
        

        Output:

        Go launched at 2009-11-10 15:00:00 -0800 PST
        

        func Now

        func Now() Time

        Now returns the current local time.

        func Parse

        func Parse(layout, value string) (Time, error)

        Parse parses a formatted string and returns the time value it represents. See the documentation for the constant called Layout to see how to represent the format. The second argument must be parseable using the format string (layout) provided as the first argument.

        The example for Time.Format demonstrates the working of the layout string in detail and is a good reference.

        When parsing (only), the input may contain a fractional second field immediately after the seconds field, even if the layout does not signify its presence. In that case either a comma or a decimal point followed by a maximal series of digits is parsed as a fractional second. Fractional seconds are truncated to nanosecond precision.

        Elements omitted from the layout are assumed to be zero or, when zero is impossible, one, so parsing "3:04pm" returns the time corresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is 0, this time is before the zero Time). Years must be in the range 0000..9999. The day of the week is checked for syntax but it is otherwise ignored.

        For layouts specifying the two-digit year 06, a value NN >= 69 will be treated as 19NN and a value NN < 69 will be treated as 20NN.

        The remainder of this comment describes the handling of time zones.

        In the absence of a time zone indicator, Parse returns a time in UTC.

        When parsing a time with a zone offset like -0700, if the offset corresponds to a time zone used by the current location (Local), then Parse uses that location and zone in the returned time. Otherwise it records the time as being in a fabricated location with time fixed at the given zone offset.

        When parsing a time with a zone abbreviation like MST, if the zone abbreviation has a defined offset in the current location, then that offset is used. The zone abbreviation "UTC" is recognized as UTC regardless of location. If the zone abbreviation is unknown, Parse records the time as being in a fabricated location with the given zone abbreviation and a zero offset. This choice means that such a time can be parsed and reformatted with the same layout losslessly, but the exact instant used in the representation will differ by the actual zone offset. To avoid such problems, prefer time layouts that use a numeric zone offset, or use ParseInLocation.

        Example

        Code:

        // See the example for Time.Format for a thorough description of how
        // to define the layout string to parse a time.Time value; Parse and
        // Format use the same model to describe their input and output.
        
        // longForm shows by example how the reference time would be represented in
        // the desired layout.
        const longForm = "Jan 2, 2006 at 3:04pm (MST)"
        t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
        fmt.Println(t)
        
        // shortForm is another way the reference time would be represented
        // in the desired layout; it has no time zone present.
        // Note: without explicit zone, returns time in UTC.
        const shortForm = "2006-Jan-02"
        t, _ = time.Parse(shortForm, "2013-Feb-03")
        fmt.Println(t)
        
        // Some valid layouts are invalid time values, due to format specifiers
        // such as _ for space padding and Z for zone information.
        // For example the RFC3339 layout 2006-01-02T15:04:05Z07:00
        // contains both Z and a time zone offset in order to handle both valid options:
        // 2006-01-02T15:04:05Z
        // 2006-01-02T15:04:05+07:00
        t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
        fmt.Println(t)
        t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05+07:00")
        fmt.Println(t)
        _, err := time.Parse(time.RFC3339, time.RFC3339)
        fmt.Println("error", err) // Returns an error as the layout is not a valid time value
        
        

        Output:

        2013-02-03 19:54:00 -0800 PST
        2013-02-03 00:00:00 +0000 UTC
        2006-01-02 15:04:05 +0000 UTC
        2006-01-02 15:04:05 +0700 +0700
        error parsing time "2006-01-02T15:04:05Z07:00": extra text: "07:00"
        

        func ParseInLocation

        func ParseInLocation(layout, value string, loc *Location) (Time, error)

        ParseInLocation is like Parse but differs in two important ways. First, in the absence of time zone information, Parse interprets a time as UTC; ParseInLocation interprets the time as in the given location. Second, when given a zone offset or abbreviation, Parse tries to match it against the Local location; ParseInLocation uses the given location.

        Example

        Code:

        loc, _ := time.LoadLocation("Europe/Berlin")
        
        // This will look for the name CEST in the Europe/Berlin time zone.
        const longForm = "Jan 2, 2006 at 3:04pm (MST)"
        t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
        fmt.Println(t)
        
        // Note: without explicit zone, returns time in given location.
        const shortForm = "2006-Jan-02"
        t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
        fmt.Println(t)
        
        

        Output:

        2012-07-09 05:02:00 +0200 CEST
        2012-07-09 00:00:00 +0200 CEST
        

        func Unix

        func Unix(sec int64, nsec int64) Time

        Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC. It is valid to pass nsec outside the range [0, 999999999]. Not all sec values have a corresponding time value. One such value is 1<<63-1 (the largest int64 value).

        Example

        Code:

        unixTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
        fmt.Println(unixTime.Unix())
        t := time.Unix(unixTime.Unix(), 0).UTC()
        fmt.Println(t)
        
        

        Output:

        1257894000
        2009-11-10 23:00:00 +0000 UTC
        

        func UnixMicro

        func UnixMicro(usec int64) Time

        UnixMicro returns the local Time corresponding to the given Unix time, usec microseconds since January 1, 1970 UTC.

        Example

        Code:

        umt := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
        fmt.Println(umt.UnixMicro())
        t := time.UnixMicro(umt.UnixMicro()).UTC()
        fmt.Println(t)
        
        

        Output:

        1257894000000000
        2009-11-10 23:00:00 +0000 UTC
        

        func UnixMilli

        func UnixMilli(msec int64) Time

        UnixMilli returns the local Time corresponding to the given Unix time, msec milliseconds since January 1, 1970 UTC.

        Example

        Code:

        umt := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
        fmt.Println(umt.UnixMilli())
        t := time.UnixMilli(umt.UnixMilli()).UTC()
        fmt.Println(t)
        
        

        Output:

        1257894000000
        2009-11-10 23:00:00 +0000 UTC
        

        func (Time) Add

        func (t Time) Add(d Duration) Time

        Add returns the time t+d.

        Example

        Code:

        start := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
        afterTenSeconds := start.Add(time.Second * 10)
        afterTenMinutes := start.Add(time.Minute * 10)
        afterTenHours := start.Add(time.Hour * 10)
        afterTenDays := start.Add(time.Hour * 24 * 10)
        
        fmt.Printf("start = %v\n", start)
        fmt.Printf("start.Add(time.Second * 10) = %v\n", afterTenSeconds)
        fmt.Printf("start.Add(time.Minute * 10) = %v\n", afterTenMinutes)
        fmt.Printf("start.Add(time.Hour * 10) = %v\n", afterTenHours)
        fmt.Printf("start.Add(time.Hour * 24 * 10) = %v\n", afterTenDays)
        
        

        Output:

        start = 2009-01-01 12:00:00 +0000 UTC
        start.Add(time.Second * 10) = 2009-01-01 12:00:10 +0000 UTC
        start.Add(time.Minute * 10) = 2009-01-01 12:10:00 +0000 UTC
        start.Add(time.Hour * 10) = 2009-01-01 22:00:00 +0000 UTC
        start.Add(time.Hour * 24 * 10) = 2009-01-11 12:00:00 +0000 UTC
        

        func (Time) AddDate

        func (t Time) AddDate(years int, months int, days int) Time

        AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.

        Note that dates are fundamentally coupled to timezones, and calendrical periods like days don't have fixed durations. AddDate uses the Location of the Time value to determine these durations. That means that the same AddDate arguments can produce a different shift in absolute time depending on the base Time value and its Location. For example, AddDate(0, 0, 1) applied to 12:00 on March 27 always returns 12:00 on March 28. At some locations and in some years this is a 24 hour shift. In others it's a 23 hour shift due to daylight savings time transitions.

        AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31.

        Example

        Code:

        start := time.Date(2023, 03, 25, 12, 0, 0, 0, time.UTC)
        oneDayLater := start.AddDate(0, 0, 1)
        dayDuration := oneDayLater.Sub(start)
        oneMonthLater := start.AddDate(0, 1, 0)
        oneYearLater := start.AddDate(1, 0, 0)
        
        zurich, err := time.LoadLocation("Europe/Zurich")
        if err != nil {
            panic(err)
        }
        // This was the day before a daylight saving time transition in Zürich.
        startZurich := time.Date(2023, 03, 25, 12, 0, 0, 0, zurich)
        oneDayLaterZurich := startZurich.AddDate(0, 0, 1)
        dayDurationZurich := oneDayLaterZurich.Sub(startZurich)
        
        fmt.Printf("oneDayLater: start.AddDate(0, 0, 1) = %v\n", oneDayLater)
        fmt.Printf("oneMonthLater: start.AddDate(0, 1, 0) = %v\n", oneMonthLater)
        fmt.Printf("oneYearLater: start.AddDate(1, 0, 0) = %v\n", oneYearLater)
        fmt.Printf("oneDayLaterZurich: startZurich.AddDate(0, 0, 1) = %v\n", oneDayLaterZurich)
        fmt.Printf("Day duration in UTC: %v | Day duration in Zürich: %v\n", dayDuration, dayDurationZurich)
        
        

        Output:

        oneDayLater: start.AddDate(0, 0, 1) = 2023-03-26 12:00:00 +0000 UTC
        oneMonthLater: start.AddDate(0, 1, 0) = 2023-04-25 12:00:00 +0000 UTC
        oneYearLater: start.AddDate(1, 0, 0) = 2024-03-25 12:00:00 +0000 UTC
        oneDayLaterZurich: startZurich.AddDate(0, 0, 1) = 2023-03-26 12:00:00 +0200 CEST
        Day duration in UTC: 24h0m0s | Day duration in Zürich: 23h0m0s
        

        func (Time) After

        func (t Time) After(u Time) bool

        After reports whether the time instant t is after u.

        Example

        Code:

        year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
        year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
        
        isYear3000AfterYear2000 := year3000.After(year2000) // True
        isYear2000AfterYear3000 := year2000.After(year3000) // False
        
        fmt.Printf("year3000.After(year2000) = %v\n", isYear3000AfterYear2000)
        fmt.Printf("year2000.After(year3000) = %v\n", isYear2000AfterYear3000)
        
        

        Output:

        year3000.After(year2000) = true
        year2000.After(year3000) = false
        

        func (Time) AppendFormat

        func (t Time) AppendFormat(b []byte, layout string) []byte

        AppendFormat is like Format but appends the textual representation to b and returns the extended buffer.

        Example

        Code:

        t := time.Date(2017, time.November, 4, 11, 0, 0, 0, time.UTC)
        text := []byte("Time: ")
        
        text = t.AppendFormat(text, time.Kitchen)
        fmt.Println(string(text))
        
        

        Output:

        Time: 11:00AM
        

        func (Time) Before

        func (t Time) Before(u Time) bool

        Before reports whether the time instant t is before u.

        Example

        Code:

        year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
        year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
        
        isYear2000BeforeYear3000 := year2000.Before(year3000) // True
        isYear3000BeforeYear2000 := year3000.Before(year2000) // False
        
        fmt.Printf("year2000.Before(year3000) = %v\n", isYear2000BeforeYear3000)
        fmt.Printf("year3000.Before(year2000) = %v\n", isYear3000BeforeYear2000)
        
        

        Output:

        year2000.Before(year3000) = true
        year3000.Before(year2000) = false
        

        func (Time) Clock

        func (t Time) Clock() (hour, min, sec int)

        Clock returns the hour, minute, and second within the day specified by t.

        func (Time) Compare

        func (t Time) Compare(u Time) int

        Compare compares the time instant t with u. If t is before u, it returns -1; if t is after u, it returns +1; if they're the same, it returns 0.

        func (Time) Date

        func (t Time) Date() (year int, month Month, day int)

        Date returns the year, month, and day in which t occurs.

        Example

        Code:

        d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
        year, month, day := d.Date()
        
        fmt.Printf("year = %v\n", year)
        fmt.Printf("month = %v\n", month)
        fmt.Printf("day = %v\n", day)
        
        

        Output:

        year = 2000
        month = February
        day = 1
        

        func (Time) Day

        func (t Time) Day() int

        Day returns the day of the month specified by t.

        Example

        Code:

        d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
        day := d.Day()
        
        fmt.Printf("day = %v\n", day)
        
        

        Output:

        day = 1
        

        func (Time) Equal

        func (t Time) Equal(u Time) bool

        Equal reports whether t and u represent the same time instant. Two times can be equal even if they are in different locations. For example, 6:00 +0200 and 4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead.

        Example

        Code:

        secondsEastOfUTC := int((8 * time.Hour).Seconds())
        beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
        
        // Unlike the equal operator, Equal is aware that d1 and d2 are the
        // same instant but in different time zones.
        d1 := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
        d2 := time.Date(2000, 2, 1, 20, 30, 0, 0, beijing)
        
        datesEqualUsingEqualOperator := d1 == d2
        datesEqualUsingFunction := d1.Equal(d2)
        
        fmt.Printf("datesEqualUsingEqualOperator = %v\n", datesEqualUsingEqualOperator)
        fmt.Printf("datesEqualUsingFunction = %v\n", datesEqualUsingFunction)
        
        

        Output:

        datesEqualUsingEqualOperator = false
        datesEqualUsingFunction = true
        

        func (Time) Format

        func (t Time) Format(layout string) string

        Format returns a textual representation of the time value formatted according to the layout defined by the argument. See the documentation for the constant called Layout to see how to represent the layout format.

        The executable example for Time.Format demonstrates the working of the layout string in detail and is a good reference.

        Example

        Code:

        // Parse a time value from a string in the standard Unix format.
        t, err := time.Parse(time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
        if err != nil { // Always check errors even if they should not happen.
            panic(err)
        }
        
        tz, err := time.LoadLocation("Asia/Shanghai")
        if err != nil { // Always check errors even if they should not happen.
            panic(err)
        }
        
        // time.Time's Stringer method is useful without any format.
        fmt.Println("default format:", t)
        
        // Predefined constants in the package implement common layouts.
        fmt.Println("Unix format:", t.Format(time.UnixDate))
        
        // The time zone attached to the time value affects its output.
        fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))
        
        fmt.Println("in Shanghai with seconds:", t.In(tz).Format("2006-01-02T15:04:05 -070000"))
        
        fmt.Println("in Shanghai with colon seconds:", t.In(tz).Format("2006-01-02T15:04:05 -07:00:00"))
        
        // The rest of this function demonstrates the properties of the
        // layout string used in the format.
        
        // The layout string used by the Parse function and Format method
        // shows by example how the reference time should be represented.
        // We stress that one must show how the reference time is formatted,
        // not a time of the user's choosing. Thus each layout string is a
        // representation of the time stamp,
        //	Jan 2 15:04:05 2006 MST
        // An easy way to remember this value is that it holds, when presented
        // in this order, the values (lined up with the elements above):
        //	  1 2  3  4  5    6  -7
        // There are some wrinkles illustrated below.
        
        // Most uses of Format and Parse use constant layout strings such as
        // the ones defined in this package, but the interface is flexible,
        // as these examples show.
        
        // Define a helper function to make the examples' output look nice.
        do := func(name, layout, want string) {
            got := t.Format(layout)
            if want != got {
                fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
                return
            }
            fmt.Printf("%-16s %q gives %q\n", name, layout, got)
        }
        
        // Print a header in our output.
        fmt.Printf("\nFormats:\n\n")
        
        // Simple starter examples.
        do("Basic full date", "Mon Jan 2 15:04:05 MST 2006", "Wed Feb 25 11:06:39 PST 2015")
        do("Basic short date", "2006/01/02", "2015/02/25")
        
        // The hour of the reference time is 15, or 3PM. The layout can express
        // it either way, and since our value is the morning we should see it as
        // an AM time. We show both in one format string. Lower case too.
        do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")
        
        // When parsing, if the seconds value is followed by a decimal point
        // and some digits, that is taken as a fraction of a second even if
        // the layout string does not represent the fractional second.
        // Here we add a fractional second to our time value used above.
        t, err = time.Parse(time.UnixDate, "Wed Feb 25 11:06:39.1234 PST 2015")
        if err != nil {
            panic(err)
        }
        // It does not appear in the output if the layout string does not contain
        // a representation of the fractional second.
        do("No fraction", time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
        
        // Fractional seconds can be printed by adding a run of 0s or 9s after
        // a decimal point in the seconds value in the layout string.
        // If the layout digits are 0s, the fractional second is of the specified
        // width. Note that the output has a trailing zero.
        do("0s for fraction", "15:04:05.00000", "11:06:39.12340")
        
        // If the fraction in the layout is 9s, trailing zeros are dropped.
        do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")
        
        

        Output:

        default format: 2015-02-25 11:06:39 -0800 PST
        Unix format: Wed Feb 25 11:06:39 PST 2015
        Same, in UTC: Wed Feb 25 19:06:39 UTC 2015
        in Shanghai with seconds: 2015-02-26T03:06:39 +080000
        in Shanghai with colon seconds: 2015-02-26T03:06:39 +08:00:00
        
        Formats:
        
        Basic full date  "Mon Jan 2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015"
        Basic short date "2006/01/02" gives "2015/02/25"
        AM/PM            "3PM==3pm==15h" gives "11AM==11am==11h"
        No fraction      "Mon Jan _2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015"
        0s for fraction  "15:04:05.00000" gives "11:06:39.12340"
        9s for fraction  "15:04:05.99999999" gives "11:06:39.1234"
        

        Example (Pad)

        Code:

        // Parse a time value from a string in the standard Unix format.
        t, err := time.Parse(time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
        if err != nil { // Always check errors even if they should not happen.
            panic(err)
        }
        
        // Define a helper function to make the examples' output look nice.
        do := func(name, layout, want string) {
            got := t.Format(layout)
            if want != got {
                fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
                return
            }
            fmt.Printf("%-16s %q gives %q\n", name, layout, got)
        }
        
        // The predefined constant Unix uses an underscore to pad the day.
        do("Unix", time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")
        
        // For fixed-width printing of values, such as the date, that may be one or
        // two characters (7 vs. 07), use an _ instead of a space in the layout string.
        // Here we print just the day, which is 2 in our layout string and 7 in our
        // value.
        do("No pad", "<2>", "<7>")
        
        // An underscore represents a space pad, if the date only has one digit.
        do("Spaces", "<_2>", "< 7>")
        
        // A "0" indicates zero padding for single-digit values.
        do("Zeros", "<02>", "<07>")
        
        // If the value is already the right width, padding is not used.
        // For instance, the second (05 in the reference time) in our value is 39,
        // so it doesn't need padding, but the minutes (04, 06) does.
        do("Suppressed pad", "04:05", "06:39")
        
        

        Output:

        Unix             "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar  7 11:06:39 PST 2015"
        No pad           "<2>" gives "<7>"
        Spaces           "<_2>" gives "< 7>"
        Zeros            "<02>" gives "<07>"
        Suppressed pad   "04:05" gives "06:39"
        

        func (Time) GoString

        func (t Time) GoString() string

        GoString implements fmt.GoStringer and formats t to be printed in Go source code.

        Example

        Code:

        t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
        fmt.Println(t.GoString())
        t = t.Add(1 * time.Minute)
        fmt.Println(t.GoString())
        t = t.AddDate(0, 1, 0)
        fmt.Println(t.GoString())
        t, _ = time.Parse("Jan 2, 2006 at 3:04pm (MST)", "Feb 3, 2013 at 7:54pm (UTC)")
        fmt.Println(t.GoString())
        
        

        Output:

        time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
        time.Date(2009, time.November, 10, 23, 1, 0, 0, time.UTC)
        time.Date(2009, time.December, 10, 23, 1, 0, 0, time.UTC)
        time.Date(2013, time.February, 3, 19, 54, 0, 0, time.UTC)
        

        func (*Time) GobDecode

        func (t *Time) GobDecode(data []byte) error

        GobDecode implements the gob.GobDecoder interface.

        func (Time) GobEncode

        func (t Time) GobEncode() ([]byte, error)

        GobEncode implements the gob.GobEncoder interface.

        func (Time) Hour

        func (t Time) Hour() int

        Hour returns the hour within the day specified by t, in the range [0, 23].

        func (Time) ISOWeek

        func (t Time) ISOWeek() (year, week int)

        ISOWeek returns the ISO 8601 year and week number in which t occurs. Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1.

        func (Time) In

        func (t Time) In(loc *Location) Time

        In returns a copy of t representing the same time instant, but with the copy's location information set to loc for display purposes.

        In panics if loc is nil.

        func (Time) IsDST

        func (t Time) IsDST() bool

        IsDST reports whether the time in the configured location is in Daylight Savings Time.

        func (Time) IsZero

        func (t Time) IsZero() bool

        IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.

        func (Time) Local

        func (t Time) Local() Time

        Local returns t with the location set to local time.

        func (Time) Location

        func (t Time) Location() *Location

        Location returns the time zone information associated with t.

        func (Time) MarshalBinary

        func (t Time) MarshalBinary() ([]byte, error)

        MarshalBinary implements the encoding.BinaryMarshaler interface.

        func (Time) MarshalJSON

        func (t Time) MarshalJSON() ([]byte, error)

        MarshalJSON implements the json.Marshaler interface. The time is a quoted string in the RFC 3339 format with sub-second precision. If the timestamp cannot be represented as valid RFC 3339 (e.g., the year is out of range), then an error is reported.

        func (Time) MarshalText

        func (t Time) MarshalText() ([]byte, error)

        MarshalText implements the encoding.TextMarshaler interface. The time is formatted in RFC 3339 format with sub-second precision. If the timestamp cannot be represented as valid RFC 3339 (e.g., the year is out of range), then an error is reported.

        func (Time) Minute

        func (t Time) Minute() int

        Minute returns the minute offset within the hour specified by t, in the range [0, 59].

        func (Time) Month

        func (t Time) Month() Month

        Month returns the month of the year specified by t.

        func (Time) Nanosecond

        func (t Time) Nanosecond() int

        Nanosecond returns the nanosecond offset within the second specified by t, in the range [0, 999999999].

        func (Time) Round

        func (t Time) Round(d Duration) Time

        Round returns the result of rounding t to the nearest multiple of d (since the zero time). The rounding behavior for halfway values is to round up. If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged.

        Round operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Round(Hour) may return a time with a non-zero minute, depending on the time's Location.

        Example

        Code:

        t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC)
        round := []time.Duration{
            time.Nanosecond,
            time.Microsecond,
            time.Millisecond,
            time.Second,
            2 * time.Second,
            time.Minute,
            10 * time.Minute,
            time.Hour,
        }
        
        for _, d := range round {
            fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))
        }
        

        Output:

        t.Round(   1ns) = 12:15:30.918273645
        t.Round(   1µs) = 12:15:30.918274
        t.Round(   1ms) = 12:15:30.918
        t.Round(    1s) = 12:15:31
        t.Round(    2s) = 12:15:30
        t.Round(  1m0s) = 12:16:00
        t.Round( 10m0s) = 12:20:00
        t.Round(1h0m0s) = 12:00:00
        

        func (Time) Second

        func (t Time) Second() int

        Second returns the second offset within the minute specified by t, in the range [0, 59].

        func (Time) String

        func (t Time) String() string

        String returns the time formatted using the format string

        "2006-01-02 15:04:05.999999999 -0700 MST"
        

        If the time has a monotonic clock reading, the returned string includes a final field "m=±<value>", where value is the monotonic clock reading formatted as a decimal number of seconds.

        The returned string is meant for debugging; for a stable serialized representation, use t.MarshalText, t.MarshalBinary, or t.Format with an explicit format string.

        Example

        Code:

        timeWithNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 15, time.UTC)
        withNanoseconds := timeWithNanoseconds.String()
        
        timeWithoutNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 0, time.UTC)
        withoutNanoseconds := timeWithoutNanoseconds.String()
        
        fmt.Printf("withNanoseconds = %v\n", string(withNanoseconds))
        fmt.Printf("withoutNanoseconds = %v\n", string(withoutNanoseconds))
        
        

        Output:

        withNanoseconds = 2000-02-01 12:13:14.000000015 +0000 UTC
        withoutNanoseconds = 2000-02-01 12:13:14 +0000 UTC
        

        func (Time) Sub

        func (t Time) Sub(u Time) Duration

        Sub returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d).

        Example

        Code:

        start := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
        end := time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC)
        
        difference := end.Sub(start)
        fmt.Printf("difference = %v\n", difference)
        
        

        Output:

        difference = 12h0m0s
        

        func (Time) Truncate

        func (t Time) Truncate(d Duration) Time

        Truncate returns the result of rounding t down to a multiple of d (since the zero time). If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged.

        Truncate operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Truncate(Hour) may return a time with a non-zero minute, depending on the time's Location.

        Example

        Code:

        t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")
        trunc := []time.Duration{
            time.Nanosecond,
            time.Microsecond,
            time.Millisecond,
            time.Second,
            2 * time.Second,
            time.Minute,
            10 * time.Minute,
        }
        
        for _, d := range trunc {
            fmt.Printf("t.Truncate(%5s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))
        }
        // To round to the last midnight in the local timezone, create a new Date.
        midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
        _ = midnight
        
        

        Output:

        t.Truncate(  1ns) = 12:15:30.918273645
        t.Truncate(  1µs) = 12:15:30.918273
        t.Truncate(  1ms) = 12:15:30.918
        t.Truncate(   1s) = 12:15:30
        t.Truncate(   2s) = 12:15:30
        t.Truncate( 1m0s) = 12:15:00
        t.Truncate(10m0s) = 12:10:00
        

        func (Time) UTC

        func (t Time) UTC() Time

        UTC returns t with the location set to UTC.

        func (Time) Unix

        func (t Time) Unix() int64

        Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. The result does not depend on the location associated with t. Unix-like operating systems often record time as a 32-bit count of seconds, but since the method here returns a 64-bit value it is valid for billions of years into the past or future.

        Example

        Code:

        // 1 billion seconds of Unix, three ways.
        fmt.Println(time.Unix(1e9, 0).UTC())     // 1e9 seconds
        fmt.Println(time.Unix(0, 1e18).UTC())    // 1e18 nanoseconds
        fmt.Println(time.Unix(2e9, -1e18).UTC()) // 2e9 seconds - 1e18 nanoseconds
        
        t := time.Date(2001, time.September, 9, 1, 46, 40, 0, time.UTC)
        fmt.Println(t.Unix())     // seconds since 1970
        fmt.Println(t.UnixNano()) // nanoseconds since 1970
        
        

        Output:

        2001-09-09 01:46:40 +0000 UTC
        2001-09-09 01:46:40 +0000 UTC
        2001-09-09 01:46:40 +0000 UTC
        1000000000
        1000000000000000000
        

        func (Time) UnixMicro

        func (t Time) UnixMicro() int64

        UnixMicro returns t as a Unix time, the number of microseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in microseconds cannot be represented by an int64 (a date before year -290307 or after year 294246). The result does not depend on the location associated with t.

        func (Time) UnixMilli

        func (t Time) UnixMilli() int64

        UnixMilli returns t as a Unix time, the number of milliseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in milliseconds cannot be represented by an int64 (a date more than 292 million years before or after 1970). The result does not depend on the location associated with t.

        func (Time) UnixNano

        func (t Time) UnixNano() int64

        UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in nanoseconds cannot be represented by an int64 (a date before the year 1678 or after 2262). Note that this means the result of calling UnixNano on the zero Time is undefined. The result does not depend on the location associated with t.

        func (*Time) UnmarshalBinary

        func (t *Time) UnmarshalBinary(data []byte) error

        UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

        func (*Time) UnmarshalJSON

        func (t *Time) UnmarshalJSON(data []byte) error

        UnmarshalJSON implements the json.Unmarshaler interface. The time must be a quoted string in the RFC 3339 format.

        func (*Time) UnmarshalText

        func (t *Time) UnmarshalText(data []byte) error

        UnmarshalText implements the encoding.TextUnmarshaler interface. The time must be in the RFC 3339 format.

        func (Time) Weekday

        func (t Time) Weekday() Weekday

        Weekday returns the day of the week specified by t.

        func (Time) Year

        func (t Time) Year() int

        Year returns the year in which t occurs.

        func (Time) YearDay

        func (t Time) YearDay() int

        YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, and [1,366] in leap years.

        func (Time) Zone

        func (t Time) Zone() (name string, offset int)

        Zone computes the time zone in effect at time t, returning the abbreviated name of the zone (such as "CET") and its offset in seconds east of UTC.

        func (Time) ZoneBounds

        func (t Time) ZoneBounds() (start, end Time)

        ZoneBounds returns the bounds of the time zone in effect at time t. The zone begins at start and the next zone begins at end. If the zone begins at the beginning of time, start will be returned as a zero Time. If the zone goes on forever, end will be returned as a zero Time. The Location of the returned times will be the same as t.

        type Timer

        The Timer type represents a single event. When the Timer expires, the current time will be sent on C, unless the Timer was created by AfterFunc. A Timer must be created with NewTimer or AfterFunc.

        type Timer struct {
            C <-chan Time
            // contains filtered or unexported fields
        }
        

        func AfterFunc

        func AfterFunc(d Duration, f func()) *Timer

        AfterFunc waits for the duration to elapse and then calls f in its own goroutine. It returns a Timer that can be used to cancel the call using its Stop method. The returned Timer's C field is not used and will be nil.

        func NewTimer

        func NewTimer(d Duration) *Timer

        NewTimer creates a new Timer that will send the current time on its channel after at least duration d.

        func (*Timer) Reset

        func (t *Timer) Reset(d Duration) bool

        Reset changes the timer to expire after duration d. It returns true if the timer had been active, false if the timer had expired or been stopped.

        For a Timer created with NewTimer, Reset should be invoked only on stopped or expired timers with drained channels.

        If a program has already received a value from t.C, the timer is known to have expired and the channel drained, so t.Reset can be used directly. If a program has not yet received a value from t.C, however, the timer must be stopped and—if Stop reports that the timer expired before being stopped—the channel explicitly drained:

        if !t.Stop() {
        	<-t.C
        }
        t.Reset(d)
        

        This should not be done concurrent to other receives from the Timer's channel.

        Note that it is not possible to use Reset's return value correctly, as there is a race condition between draining the channel and the new timer expiring. Reset should always be invoked on stopped or expired channels, as described above. The return value exists to preserve compatibility with existing programs.

        For a Timer created with AfterFunc(d, f), Reset either reschedules when f will run, in which case Reset returns true, or schedules f to run again, in which case it returns false. When Reset returns false, Reset neither waits for the prior f to complete before returning nor does it guarantee that the subsequent goroutine running f does not run concurrently with the prior one. If the caller needs to know whether the prior execution of f is completed, it must coordinate with f explicitly.

        func (*Timer) Stop

        func (t *Timer) Stop() bool

        Stop prevents the Timer from firing. It returns true if the call stops the timer, false if the timer has already expired or been stopped. Stop does not close the channel, to prevent a read from the channel succeeding incorrectly.

        To ensure the channel is empty after a call to Stop, check the return value and drain the channel. For example, assuming the program has not received from t.C already:

        if !t.Stop() {
        	<-t.C
        }
        

        This cannot be done concurrent to other receives from the Timer's channel or other calls to the Timer's Stop method.

        For a timer created with AfterFunc(d, f), if t.Stop returns false, then the timer has already expired and the function f has been started in its own goroutine; Stop does not wait for f to complete before returning. If the caller needs to know whether f is completed, it must coordinate with f explicitly.

        type Weekday

        A Weekday specifies a day of the week (Sunday = 0, ...).

        type Weekday int
        const (
            Sunday Weekday = iota
            Monday
            Tuesday
            Wednesday
            Thursday
            Friday
            Saturday
        )

        func (Weekday) String

        func (d Weekday) String() string

        String returns the English name of the day ("Sunday", "Monday", ...).

        Subdirectories

        Name Synopsis
        ..
        tzdata Package tzdata provides an embedded copy of the timezone database.
        zmq4 - Go Documentation Server
        ...

        Package zmq4

        import "github.com/pebbe/zmq4"
        Overview
        Index
        Subdirectories

        Overview ▾

        A Go interface to ZeroMQ (zmq, 0mq) version 4.

        For ZeroMQ version 3, see: http://github.com/pebbe/zmq3

        For ZeroMQ version 2, see: http://github.com/pebbe/zmq2

        http://www.zeromq.org/

        See also the wiki: https://github.com/pebbe/zmq4/wiki

        ----

        A note on the use of a context:

        This package provides a default context. This is what will be used by the functions without a context receiver, that create a socket or manipulate the context. Package developers that import this package should probably not use the default context with its associated functions, but create their own context(s). See: type Context.

        ----

        Since Go 1.14 you will get a lot of interrupted system calls.

        See: https://golang.org/doc/go1.14#runtime

        There are two options to prevent this.

        The first option is to build your program with the environment variable:

        GODEBUG=asyncpreemptoff=1
        

        The second option is to let the program retry after an interrupted system call.

        Initially, this is set to true, for the global context, and for contexts created with NewContext().

        When you install a signal handler, for instance to handle Ctrl-C, you should probably clear this option in your signal handler. For example:

        zctx, _ := zmq.NewContext()
        
        ctx, cancel := context.WithCancel(context.Background())
        
        go func() {
            chSignal := make(chan os.Signal, 1)
            signal.Notify(chSignal, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
            <-chSignal
            zmq4.SetRetryAfterEINTR(false)
            zctx.SetRetryAfterEINTR(false)
            cancel()
        }()
        

        ----

        Index ▾

        Constants
        Variables
        func AuthAllow(domain string, addresses ...string)
        func AuthCurveAdd(domain string, pubkeys ...string)
        func AuthCurvePublic(z85SecretKey string) (z85PublicKey string, err error)
        func AuthCurveRemove(domain string, pubkeys ...string)
        func AuthCurveRemoveAll(domain string)
        func AuthDeny(domain string, addresses ...string)
        func AuthMetaBlob(key, value string) (blob []byte, err error)
        func AuthPlainAdd(domain, username, password string)
        func AuthPlainRemove(domain string, usernames ...string)
        func AuthPlainRemoveAll(domain string)
        func AuthSetMetadataHandler(handler func(version, request_id, domain, address, identity, mechanism string, credentials ...string) (metadata map[string]string))
        func AuthSetVerbose(verbose bool)
        func AuthStart() (err error)
        func AuthStop()
        func Error(e int) string
        func GetBlocky() (bool, error)
        func GetIoThreads() (int, error)
        func GetIpv6() (bool, error)
        func GetMaxMsgsz() (int, error)
        func GetMaxSockets() (int, error)
        func GetRetryAfterEINTR() bool
        func HasCurve() bool
        func HasGssapi() bool
        func HasIpc() bool
        func HasNorm() bool
        func HasPgm() bool
        func HasTipc() bool
        func NewCurveKeypair() (z85_public_key, z85_secret_key string, err error)
        func Proxy(frontend, backend, capture *Socket) error
        func ProxySteerable(frontend, backend, capture, control *Socket) error
        func SetBlocky(i bool) error
        func SetIoThreads(n int) error
        func SetIpv6(i bool) error
        func SetMaxMsgsz(n int) error
        func SetMaxSockets(n int) error
        func SetRetryAfterEINTR(retry bool)
        func SetThreadPriority(n int) error
        func SetThreadSchedPolicy(n int) error
        func Term() error
        func Version() (major, minor, patch int)
        func Z85decode(s string) string
        func Z85encode(data string) string
        type Context
            func NewContext() (ctx *Context, err error)
            func (ctx *Context) GetBlocky() (bool, error)
            func (ctx *Context) GetIoThreads() (int, error)
            func (ctx *Context) GetIpv6() (bool, error)
            func (ctx *Context) GetMaxMsgsz() (int, error)
            func (ctx *Context) GetMaxSockets() (int, error)
            func (ctx *Context) GetRetryAfterEINTR() bool
            func (ctx *Context) NewSocket(t Type) (soc *Socket, err error)
            func (ctx *Context) SetBlocky(i bool) error
            func (ctx *Context) SetIoThreads(n int) error
            func (ctx *Context) SetIpv6(i bool) error
            func (ctx *Context) SetMaxMsgsz(n int) error
            func (ctx *Context) SetMaxSockets(n int) error
            func (ctx *Context) SetRetryAfterEINTR(retry bool)
            func (ctx *Context) SetThreadPriority(n int) error
            func (ctx *Context) SetThreadSchedPolicy(n int) error
            func (ctx *Context) Term() error
        type Errno
            func AsErrno(err error) Errno
            func (errno Errno) Error() string
        type Event
            func (e Event) String() string
        type Flag
            func (f Flag) String() string
        type Mechanism
            func (m Mechanism) String() string
        type Polled
        type Poller
            func NewPoller() *Poller
            func (p *Poller) Add(soc *Socket, events State) int
            func (p *Poller) Poll(timeout time.Duration) ([]Polled, error)
            func (p *Poller) PollAll(timeout time.Duration) ([]Polled, error)
            func (p *Poller) Remove(id int) error
            func (p *Poller) RemoveBySocket(soc *Socket) error
            func (p *Poller) String() string
            func (p *Poller) Update(id int, events State) (previous State, err error)
            func (p *Poller) UpdateBySocket(soc *Socket, events State) (previous State, err error)
        type Reactor
            func NewReactor() *Reactor
            func (r *Reactor) AddChannel(ch <-chan interface{}, limit int, handler func(interface{}) error) (id uint64)
            func (r *Reactor) AddChannelTime(ch <-chan time.Time, limit int, handler func(interface{}) error) (id uint64)
            func (r *Reactor) AddSocket(soc *Socket, events State, handler func(State) error)
            func (r *Reactor) RemoveChannel(id uint64)
            func (r *Reactor) RemoveSocket(soc *Socket)
            func (r *Reactor) Run(interval time.Duration) (err error)
            func (r *Reactor) SetVerbose(verbose bool)
        type Socket
            func NewSocket(t Type) (soc *Socket, err error)
            func (soc *Socket) Bind(endpoint string) error
            func (client *Socket) ClientAuthCurve(server_public_key, client_public_key, client_secret_key string) error
            func (client *Socket) ClientAuthPlain(username, password string) error
            func (soc *Socket) Close() error
            func (soc *Socket) Connect(endpoint string) error
            func (soc *Socket) Context() (*Context, error)
            func (soc *Socket) Disconnect(endpoint string) error
            func (soc *Socket) GetAffinity() (uint64, error)
            func (soc *Socket) GetBacklog() (int, error)
            func (soc *Socket) GetConnectTimeout() (time.Duration, error)
            func (soc *Socket) GetCurvePublickeyRaw() (string, error)
            func (soc *Socket) GetCurvePublickeykeyZ85() (string, error)
            func (soc *Socket) GetCurveSecretkeyRaw() (string, error)
            func (soc *Socket) GetCurveSecretkeyZ85() (string, error)
            func (soc *Socket) GetCurveServerkeyRaw() (string, error)
            func (soc *Socket) GetCurveServerkeyZ85() (string, error)
            func (soc *Socket) GetEvents() (State, error)
            func (soc *Socket) GetFd() (int, error)
            func (soc *Socket) GetGssapiPlaintext() (bool, error)
            func (soc *Socket) GetGssapiPrincipal() (string, error)
            func (soc *Socket) GetGssapiServer() (bool, error)
            func (soc *Socket) GetGssapiServicePrincipal() (string, error)
            func (soc *Socket) GetHandshakeIvl() (time.Duration, error)
            func (soc *Socket) GetIdentity() (string, error)
            func (soc *Socket) GetImmediate() (bool, error)
            func (soc *Socket) GetInvertMatching() (int, error)
            func (soc *Socket) GetIpv6() (bool, error)
            func (soc *Socket) GetLastEndpoint() (string, error)
            func (soc *Socket) GetLinger() (time.Duration, error)
            func (soc *Socket) GetMaxmsgsize() (int64, error)
            func (soc *Socket) GetMechanism() (Mechanism, error)
            func (soc *Socket) GetMulticastHops() (int, error)
            func (soc *Socket) GetMulticastMaxtpdu() (int, error)
            func (soc *Socket) GetPlainPassword() (string, error)
            func (soc *Socket) GetPlainServer() (int, error)
            func (soc *Socket) GetPlainUsername() (string, error)
            func (soc *Socket) GetRate() (int, error)
            func (soc *Socket) GetRcvbuf() (int, error)
            func (soc *Socket) GetRcvhwm() (int, error)
            func (soc *Socket) GetRcvmore() (bool, error)
            func (soc *Socket) GetRcvtimeo() (time.Duration, error)
            func (soc *Socket) GetReconnectIvl() (time.Duration, error)
            func (soc *Socket) GetReconnectIvlMax() (time.Duration, error)
            func (soc *Socket) GetRecoveryIvl() (time.Duration, error)
            func (soc *Socket) GetSndbuf() (int, error)
            func (soc *Socket) GetSndhwm() (int, error)
            func (soc *Socket) GetSndtimeo() (time.Duration, error)
            func (soc *Socket) GetSocksProxy() (string, error)
            func (soc *Socket) GetTcpKeepalive() (int, error)
            func (soc *Socket) GetTcpKeepaliveCnt() (int, error)
            func (soc *Socket) GetTcpKeepaliveIdle() (int, error)
            func (soc *Socket) GetTcpKeepaliveIntvl() (int, error)
            func (soc *Socket) GetTcpMaxrt() (time.Duration, error)
            func (soc *Socket) GetThreadSafe() (bool, error)
            func (soc *Socket) GetTos() (int, error)
            func (soc *Socket) GetType() (Type, error)
            func (soc *Socket) GetVmciBufferMaxSize() (uint64, error)
            func (soc *Socket) GetVmciBufferMinSize() (uint64, error)
            func (soc *Socket) GetVmciBufferSize() (uint64, error)
            func (soc *Socket) GetVmciConnectTimeout() (time.Duration, error)
            func (soc *Socket) GetZapDomain() (string, error)
            func (soc *Socket) Getusefd() (int, error)
            func (soc *Socket) Monitor(addr string, events Event) error
            func (soc *Socket) Recv(flags Flag) (string, error)
            func (soc *Socket) RecvBytes(flags Flag) ([]byte, error)
            func (soc *Socket) RecvBytesWithMetadata(flags Flag, properties ...string) (msg []byte, metadata map[string]string, err error)
            func (soc *Socket) RecvEvent(flags Flag) (event_type Event, addr string, value int, err error)
            func (soc *Socket) RecvMessage(flags Flag) (msg []string, err error)
            func (soc *Socket) RecvMessageBytes(flags Flag) (msg [][]byte, err error)
            func (soc *Socket) RecvMessageBytesWithMetadata(flags Flag, properties ...string) (msg [][]byte, metadata map[string]string, err error)
            func (soc *Socket) RecvMessageWithMetadata(flags Flag, properties ...string) (msg []string, metadata map[string]string, err error)
            func (soc *Socket) RecvWithMetadata(flags Flag, properties ...string) (msg string, metadata map[string]string, err error)
            func (soc *Socket) Send(data string, flags Flag) (int, error)
            func (soc *Socket) SendBytes(data []byte, flags Flag) (int, error)
            func (soc *Socket) SendMessage(parts ...interface{}) (total int, err error)
            func (soc *Socket) SendMessageDontwait(parts ...interface{}) (total int, err error)
            func (server *Socket) ServerAuthCurve(domain, secret_key string) error
            func (server *Socket) ServerAuthNull(domain string) error
            func (server *Socket) ServerAuthPlain(domain string) error
            func (soc *Socket) SetAffinity(value uint64) error
            func (soc *Socket) SetBacklog(value int) error
            func (soc *Socket) SetConflate(value bool) error
            func (soc *Socket) SetConnectRid(value string) error
            func (soc *Socket) SetConnectTimeout(value time.Duration) error
            func (soc *Socket) SetCurvePublickey(key string) error
            func (soc *Socket) SetCurveSecretkey(key string) error
            func (soc *Socket) SetCurveServer(value int) error
            func (soc *Socket) SetCurveServerkey(key string) error
            func (soc *Socket) SetGssapiPlaintext(value bool) error
            func (soc *Socket) SetGssapiPrincipal(value string) error
            func (soc *Socket) SetGssapiServer(value bool) error
            func (soc *Socket) SetGssapiServicePrincipal(value string) error
            func (soc *Socket) SetHandshakeIvl(value time.Duration) error
            func (soc *Socket) SetHeartbeatIvl(value time.Duration) error
            func (soc *Socket) SetHeartbeatTimeout(value time.Duration) error
            func (soc *Socket) SetHeartbeatTtl(value time.Duration) error
            func (soc *Socket) SetIdentity(value string) error
            func (soc *Socket) SetImmediate(value bool) error
            func (soc *Socket) SetInvertMatching(value int) error
            func (soc *Socket) SetIpv6(value bool) error
            func (soc *Socket) SetLinger(value time.Duration) error
            func (soc *Socket) SetMaxmsgsize(value int64) error
            func (soc *Socket) SetMulticastHops(value int) error
            func (soc *Socket) SetMulticastMaxtpdu(value int) error
            func (soc *Socket) SetPlainPassword(password string) error
            func (soc *Socket) SetPlainServer(value int) error
            func (soc *Socket) SetPlainUsername(username string) error
            func (soc *Socket) SetProbeRouter(value int) error
            func (soc *Socket) SetRate(value int) error
            func (soc *Socket) SetRcvbuf(value int) error
            func (soc *Socket) SetRcvhwm(value int) error
            func (soc *Socket) SetRcvtimeo(value time.Duration) error
            func (soc *Socket) SetReconnectIvl(value time.Duration) error
            func (soc *Socket) SetReconnectIvlMax(value time.Duration) error
            func (soc *Socket) SetRecoveryIvl(value time.Duration) error
            func (soc *Socket) SetReqCorrelate(value int) error
            func (soc *Socket) SetReqRelaxed(value int) error
            func (soc *Socket) SetRouterHandover(value bool) error
            func (soc *Socket) SetRouterMandatory(value int) error
            func (soc *Socket) SetRouterRaw(value int) error
            func (soc *Socket) SetSndbuf(value int) error
            func (soc *Socket) SetSndhwm(value int) error
            func (soc *Socket) SetSndtimeo(value time.Duration) error
            func (soc *Socket) SetSocksProxy(value string) error
            func (soc *Socket) SetStreamNotify(value int) error
            func (soc *Socket) SetSubscribe(filter string) error
            func (soc *Socket) SetTcpAcceptFilter(filter string) error
            func (soc *Socket) SetTcpKeepalive(value int) error
            func (soc *Socket) SetTcpKeepaliveCnt(value int) error
            func (soc *Socket) SetTcpKeepaliveIdle(value int) error
            func (soc *Socket) SetTcpKeepaliveIntvl(value int) error
            func (soc *Socket) SetTcpMaxrt(value time.Duration) error
            func (soc *Socket) SetTos(value int) error
            func (soc *Socket) SetUnsubscribe(filter string) error
            func (soc *Socket) SetUseFd(value int) error
            func (soc *Socket) SetVmciBufferMaxSize(value uint64) error
            func (soc *Socket) SetVmciBufferMinSize(value uint64) error
            func (soc *Socket) SetVmciBufferSize(value uint64) error
            func (soc *Socket) SetVmciConnectTimeout(value time.Duration) error
            func (soc *Socket) SetXpubManual(value int) error
            func (soc *Socket) SetXpubNodrop(value bool) error
            func (soc *Socket) SetXpubVerbose(value int) error
            func (soc *Socket) SetXpubVerboser(value int) error
            func (soc *Socket) SetXpubWelcomeMsg(value string) error
            func (soc *Socket) SetZapDomain(domain string) error
            func (soc Socket) String() string
            func (soc *Socket) Unbind(endpoint string) error
        type State
            func (s State) String() string
        type Type
            func (t Type) String() string

        Package files

        auth.go ctxoptions_unix.go doc.go errors.go polling.go reactor.go socketget.go socketget_unix.go socketset.go utils.go wrappers_unix.go zmq4.go

        Constants

        const (
        
            // On Windows platform some of the standard POSIX errnos are not defined.
            EADDRINUSE      = Errno(C.EADDRINUSE)
            EADDRNOTAVAIL   = Errno(C.EADDRNOTAVAIL)
            EAFNOSUPPORT    = Errno(C.EAFNOSUPPORT)
            ECONNABORTED    = Errno(C.ECONNABORTED)
            ECONNREFUSED    = Errno(C.ECONNREFUSED)
            ECONNRESET      = Errno(C.ECONNRESET)
            EHOSTUNREACH    = Errno(C.EHOSTUNREACH)
            EINPROGRESS     = Errno(C.EINPROGRESS)
            EMSGSIZE        = Errno(C.EMSGSIZE)
            ENETDOWN        = Errno(C.ENETDOWN)
            ENETRESET       = Errno(C.ENETRESET)
            ENETUNREACH     = Errno(C.ENETUNREACH)
            ENOBUFS         = Errno(C.ENOBUFS)
            ENOTCONN        = Errno(C.ENOTCONN)
            ENOTSOCK        = Errno(C.ENOTSOCK)
            ENOTSUP         = Errno(C.ENOTSUP)
            EPROTONOSUPPORT = Errno(C.EPROTONOSUPPORT)
            ETIMEDOUT       = Errno(C.ETIMEDOUT)
        
            // Native 0MQ error codes.
            EFSM           = Errno(C.EFSM)
            EMTHREAD       = Errno(C.EMTHREAD)
            ENOCOMPATPROTO = Errno(C.ENOCOMPATPROTO)
            ETERM          = Errno(C.ETERM)
        )
        const (
            MaxSocketsDflt = int(C.ZMQ_MAX_SOCKETS_DFLT)
            IoThreadsDflt  = int(C.ZMQ_IO_THREADS_DFLT)
        )
        const (
            // Constants for NewSocket()
            // See: http://api.zeromq.org/4-1:zmq-socket#toc3
            REQ    = Type(C.ZMQ_REQ)
            REP    = Type(C.ZMQ_REP)
            DEALER = Type(C.ZMQ_DEALER)
            ROUTER = Type(C.ZMQ_ROUTER)
            PUB    = Type(C.ZMQ_PUB)
            SUB    = Type(C.ZMQ_SUB)
            XPUB   = Type(C.ZMQ_XPUB)
            XSUB   = Type(C.ZMQ_XSUB)
            PUSH   = Type(C.ZMQ_PUSH)
            PULL   = Type(C.ZMQ_PULL)
            PAIR   = Type(C.ZMQ_PAIR)
            STREAM = Type(C.ZMQ_STREAM)
        )
        const (
            // Flags for (*Socket)Send(), (*Socket)Recv()
            // For Send, see: http://api.zeromq.org/4-1:zmq-send#toc2
            // For Recv, see: http://api.zeromq.org/4-1:zmq-msg-recv#toc2
            DONTWAIT = Flag(C.ZMQ_DONTWAIT)
            SNDMORE  = Flag(C.ZMQ_SNDMORE)
        )
        const (
            // Flags for (*Socket)Monitor() and (*Socket)RecvEvent()
            // See: http://api.zeromq.org/4-3:zmq-socket-monitor#toc3
            EVENT_ALL                        = Event(C.ZMQ_EVENT_ALL)
            EVENT_CONNECTED                  = Event(C.ZMQ_EVENT_CONNECTED)
            EVENT_CONNECT_DELAYED            = Event(C.ZMQ_EVENT_CONNECT_DELAYED)
            EVENT_CONNECT_RETRIED            = Event(C.ZMQ_EVENT_CONNECT_RETRIED)
            EVENT_LISTENING                  = Event(C.ZMQ_EVENT_LISTENING)
            EVENT_BIND_FAILED                = Event(C.ZMQ_EVENT_BIND_FAILED)
            EVENT_ACCEPTED                   = Event(C.ZMQ_EVENT_ACCEPTED)
            EVENT_ACCEPT_FAILED              = Event(C.ZMQ_EVENT_ACCEPT_FAILED)
            EVENT_CLOSED                     = Event(C.ZMQ_EVENT_CLOSED)
            EVENT_CLOSE_FAILED               = Event(C.ZMQ_EVENT_CLOSE_FAILED)
            EVENT_DISCONNECTED               = Event(C.ZMQ_EVENT_DISCONNECTED)
            EVENT_MONITOR_STOPPED            = Event(C.ZMQ_EVENT_MONITOR_STOPPED)
            EVENT_HANDSHAKE_FAILED_NO_DETAIL = Event(C.ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL)
            EVENT_HANDSHAKE_SUCCEEDED        = Event(C.ZMQ_EVENT_HANDSHAKE_SUCCEEDED)
            EVENT_HANDSHAKE_FAILED_PROTOCOL  = Event(C.ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL)
            EVENT_HANDSHAKE_FAILED_AUTH      = Event(C.ZMQ_EVENT_HANDSHAKE_FAILED_AUTH)
        )
        const (
            // Flags for (*Socket)GetEvents()
            // See: http://api.zeromq.org/4-1:zmq-getsockopt#toc8
            POLLIN  = State(C.ZMQ_POLLIN)
            POLLOUT = State(C.ZMQ_POLLOUT)
        )
        const (
            // Constants for (*Socket)GetMechanism()
            // See: http://api.zeromq.org/4-1:zmq-getsockopt#toc22
            NULL   = Mechanism(C.ZMQ_NULL)
            PLAIN  = Mechanism(C.ZMQ_PLAIN)
            CURVE  = Mechanism(C.ZMQ_CURVE)
            GSSAPI = Mechanism(C.ZMQ_GSSAPI)
        )
        const CURVE_ALLOW_ANY = "*"

        Variables

        var (
            ErrorContextClosed         = errors.New("Context is closed")
            ErrorSocketClosed          = errors.New("Socket is closed")
            ErrorMoreExpected          = errors.New("More expected")
            ErrorNotImplemented405     = errors.New("Not implemented, requires 0MQ version 4.0.5")
            ErrorNotImplemented41      = errors.New("Not implemented, requires 0MQ version 4.1")
            ErrorNotImplemented42      = errors.New("Not implemented, requires 0MQ version 4.2")
            ErrorNotImplementedWindows = errors.New("Not implemented on Windows")
            ErrorNoSocket              = errors.New("No such socket")
        )

        func AuthAllow

        func AuthAllow(domain string, addresses ...string)

        Allow (whitelist) some addresses for a domain.

        An address can be a single IP address, or an IP address and mask in CIDR notation.

        For NULL, all clients from these addresses will be accepted.

        For PLAIN and CURVE, they will be allowed to continue with authentication.

        You can call this method multiple times to whitelist multiple IP addresses.

        If you whitelist a single address for a domain, any non-whitelisted addresses for that domain are treated as blacklisted.

        Use domain "*" for all domains.

        For backward compatibility: if domain can be parsed as an IP address, it will be interpreted as another address, and it and all remaining addresses will be added to all domains.

        func AuthCurveAdd

        func AuthCurveAdd(domain string, pubkeys ...string)

        Add public user keys for CURVE authentication for a given domain.

        To cover all domains, use "*".

        Public keys are in Z85 printable text format.

        To allow all client keys without checking, specify CURVE_ALLOW_ANY for the key.

        func AuthCurvePublic

        func AuthCurvePublic(z85SecretKey string) (z85PublicKey string, err error)

        Helper function to derive z85 public key from secret key

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        func AuthCurveRemove

        func AuthCurveRemove(domain string, pubkeys ...string)

        Remove user keys from CURVE authentication for a given domain.

        func AuthCurveRemoveAll

        func AuthCurveRemoveAll(domain string)

        Remove all user keys from CURVE authentication for a given domain.

        func AuthDeny

        func AuthDeny(domain string, addresses ...string)

        Deny (blacklist) some addresses for a domain.

        An address can be a single IP address, or an IP address and mask in CIDR notation.

        For all security mechanisms, this rejects the connection without any further authentication.

        Use either a whitelist for a domain, or a blacklist for a domain, not both. If you define both a whitelist and a blacklist for a domain, only the whitelist takes effect.

        Use domain "*" for all domains.

        For backward compatibility: if domain can be parsed as an IP address, it will be interpreted as another address, and it and all remaining addresses will be added to all domains.

        func AuthMetaBlob

        func AuthMetaBlob(key, value string) (blob []byte, err error)

        This encodes a key/value pair into the format used by a ZAP handler.

        Returns an error if key is more then 255 characters long.

        func AuthPlainAdd

        func AuthPlainAdd(domain, username, password string)

        Add a user for PLAIN authentication for a given domain.

        Set `domain` to "*" to apply to all domains.

        func AuthPlainRemove

        func AuthPlainRemove(domain string, usernames ...string)

        Remove users from PLAIN authentication for a given domain.

        func AuthPlainRemoveAll

        func AuthPlainRemoveAll(domain string)

        Remove all users from PLAIN authentication for a given domain.

        func AuthSetMetadataHandler

        func AuthSetMetadataHandler(
            handler func(
                version, request_id, domain, address, identity, mechanism string, credentials ...string) (metadata map[string]string))

        This function sets the metadata handler that is called by the ZAP handler to retrieve key/value properties that should be set on reply messages in case of a status code "200" (succes).

        Default properties are `Socket-Type`, which is already set, and `Identity` and `User-Id` that are empty by default. The last two can be set, and more properties can be added.

        The `User-Id` property is used for the `user id` frame of the reply message. All other properties are stored in the `metadata` frame of the reply message.

        The default handler returns an empty map.

        For the meaning of the handler arguments, and other details, see: http://rfc.zeromq.org/spec:27#toc10

        func AuthSetVerbose

        func AuthSetVerbose(verbose bool)

        Enable verbose tracing of commands and activity.

        func AuthStart

        func AuthStart() (err error)

        Start authentication.

        Note that until you add policies, all incoming NULL connections are allowed (classic ZeroMQ behaviour), and all PLAIN and CURVE connections are denied.

        func AuthStop

        func AuthStop()

        Stop authentication.

        func Error

        func Error(e int) string

        Get 0MQ error message string.

        func GetBlocky

        func GetBlocky() (bool, error)

        Returns the blocky setting in the default context.

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        func GetIoThreads

        func GetIoThreads() (int, error)

        Returns the size of the 0MQ thread pool in the default context.

        func GetIpv6

        func GetIpv6() (bool, error)

        Returns the IPv6 option in the default context.

        func GetMaxMsgsz

        func GetMaxMsgsz() (int, error)

        Returns the maximum message size in the default context.

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        func GetMaxSockets

        func GetMaxSockets() (int, error)

        Returns the maximum number of sockets allowed in the default context.

        func GetRetryAfterEINTR

        func GetRetryAfterEINTR() bool

        Returns the retry after EINTR setting in the default context.

        func HasCurve

        func HasCurve() bool

        Returns false for ZeroMQ version < 4.1.0

        Else: returns true if the library supports the CURVE security mechanism

        func HasGssapi

        func HasGssapi() bool

        Returns false for ZeroMQ version < 4.1.0

        Else: returns true if the library supports the GSSAPI security mechanism

        func HasIpc

        func HasIpc() bool

        Returns false for ZeroMQ version < 4.1.0

        Else: returns true if the library supports the ipc:// protocol

        func HasNorm

        func HasNorm() bool

        Returns false for ZeroMQ version < 4.1.0

        Else: returns true if the library supports the norm:// protocol

        func HasPgm

        func HasPgm() bool

        Returns false for ZeroMQ version < 4.1.0

        Else: returns true if the library supports the pgm:// protocol

        func HasTipc

        func HasTipc() bool

        Returns false for ZeroMQ version < 4.1.0

        Else: returns true if the library supports the tipc:// protocol

        func NewCurveKeypair

        func NewCurveKeypair() (z85_public_key, z85_secret_key string, err error)

        Generate a new CURVE keypair

        See: http://api.zeromq.org/4-1:zmq-curve-keypair#toc2

        func Proxy

        func Proxy(frontend, backend, capture *Socket) error

        Start built-in ØMQ proxy

        See: http://api.zeromq.org/4-1:zmq-proxy#toc2

        func ProxySteerable

        func ProxySteerable(frontend, backend, capture, control *Socket) error

        Start built-in ØMQ proxy with PAUSE/RESUME/TERMINATE control flow

        Returns ErrorNotImplemented405 with ZeroMQ version < 4.0.5

        See: http://api.zeromq.org/4-1:zmq-proxy-steerable#toc2

        func SetBlocky

        func SetBlocky(i bool) error

        Sets the blocky behavior in the default context.

        See: http://api.zeromq.org/4-2:zmq-ctx-set#toc3

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        func SetIoThreads

        func SetIoThreads(n int) error

        Specifies the size of the 0MQ thread pool to handle I/O operations in the default context. If your application is using only the inproc transport for messaging you may set this to zero, otherwise set it to at least one. This option only applies before creating any sockets.

        Default value: 1

        func SetIpv6

        func SetIpv6(i bool) error

        Sets the IPv6 value for all sockets created in the default context from this point onwards. A value of true means IPv6 is enabled, while false means the socket will use only IPv4. When IPv6 is enabled, a socket will connect to, or accept connections from, both IPv4 and IPv6 hosts.

        Default value: false

        func SetMaxMsgsz

        func SetMaxMsgsz(n int) error

        Set maximum message size in the default context.

        Default value: INT_MAX

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        func SetMaxSockets

        func SetMaxSockets(n int) error

        Sets the maximum number of sockets allowed in the default context.

        Default value: 1024

        func SetRetryAfterEINTR

        func SetRetryAfterEINTR(retry bool)

        Sets the retry after EINTR setting in the default context.

        Initital value is true.

        func SetThreadPriority

        func SetThreadPriority(n int) error

        Sets scheduling priority for default context’s thread pool.

        This option requires ZeroMQ version 4.1, and is not available on Windows.

        Supported values for this option depend on chosen scheduling policy. Details can be found in sched.h file, or at http://man7.org/linux/man-pages/man2/sched_setscheduler.2.html

        This option only applies before creating any sockets on the context.

        Default value: -1

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        Returns ErrorNotImplementedWindows on Windows

        func SetThreadSchedPolicy

        func SetThreadSchedPolicy(n int) error

        Sets the scheduling policy for default context’s thread pool.

        This option requires ZeroMQ version 4.1, and is not available on Windows.

        Supported values for this option can be found in sched.h file, or at http://man7.org/linux/man-pages/man2/sched_setscheduler.2.html

        This option only applies before creating any sockets on the context.

        Default value: -1

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        Returns ErrorNotImplementedWindows on Windows

        func Term

        func Term() error

        Terminates the default context.

        For linger behavior, see: http://api.zeromq.org/4-1:zmq-ctx-term

        func Version

        func Version() (major, minor, patch int)

        Report 0MQ library version.

        func Z85decode

        func Z85decode(s string) string

        Decode a binary key from Z85 printable text

        See: http://api.zeromq.org/4-1:zmq-z85-decode

        func Z85encode

        func Z85encode(data string) string

        Encode a binary key as Z85 printable text

        See: http://api.zeromq.org/4-1:zmq-z85-encode

        type Context

        A context that is not the default context.

        type Context struct {
            // contains filtered or unexported fields
        }
        

        func NewContext

        func NewContext() (ctx *Context, err error)

        Create a new context.

        func (*Context) GetBlocky

        func (ctx *Context) GetBlocky() (bool, error)

        Returns the blocky setting.

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        func (*Context) GetIoThreads

        func (ctx *Context) GetIoThreads() (int, error)

        Returns the size of the 0MQ thread pool.

        func (*Context) GetIpv6

        func (ctx *Context) GetIpv6() (bool, error)

        Returns the IPv6 option.

        func (*Context) GetMaxMsgsz

        func (ctx *Context) GetMaxMsgsz() (int, error)

        Returns the maximum message size.

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        func (*Context) GetMaxSockets

        func (ctx *Context) GetMaxSockets() (int, error)

        Returns the maximum number of sockets allowed.

        func (*Context) GetRetryAfterEINTR

        func (ctx *Context) GetRetryAfterEINTR() bool

        Returns the retry after EINTR setting.

        func (*Context) NewSocket

        func (ctx *Context) NewSocket(t Type) (soc *Socket, err error)

        Create 0MQ socket in the given context.

        WARNING: The Socket is not thread safe. This means that you cannot access the same Socket from different goroutines without using something like a mutex.

        For a description of socket types, see: http://api.zeromq.org/4-1:zmq-socket#toc3

        func (*Context) SetBlocky

        func (ctx *Context) SetBlocky(i bool) error

        Sets the blocky behavior.

        See: http://api.zeromq.org/4-2:zmq-ctx-set#toc3

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        func (*Context) SetIoThreads

        func (ctx *Context) SetIoThreads(n int) error

        Specifies the size of the 0MQ thread pool to handle I/O operations. If your application is using only the inproc transport for messaging you may set this to zero, otherwise set it to at least one. This option only applies before creating any sockets.

        Default value: 1

        func (*Context) SetIpv6

        func (ctx *Context) SetIpv6(i bool) error

        Sets the IPv6 value for all sockets created in the context from this point onwards. A value of true means IPv6 is enabled, while false means the socket will use only IPv4. When IPv6 is enabled, a socket will connect to, or accept connections from, both IPv4 and IPv6 hosts.

        Default value: false

        func (*Context) SetMaxMsgsz

        func (ctx *Context) SetMaxMsgsz(n int) error

        Set maximum message size.

        Default value: INT_MAX

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        func (*Context) SetMaxSockets

        func (ctx *Context) SetMaxSockets(n int) error

        Sets the maximum number of sockets allowed.

        Default value: 1024

        func (*Context) SetRetryAfterEINTR

        func (ctx *Context) SetRetryAfterEINTR(retry bool)

        Sets the retry after EINTR setting.

        Initital value is true.

        func (*Context) SetThreadPriority

        func (ctx *Context) SetThreadPriority(n int) error

        Sets scheduling priority for internal context’s thread pool.

        This option requires ZeroMQ version 4.1, and is not available on Windows.

        Supported values for this option depend on chosen scheduling policy. Details can be found in sched.h file, or at http://man7.org/linux/man-pages/man2/sched_setscheduler.2.html

        This option only applies before creating any sockets on the context.

        Default value: -1

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        Returns ErrorNotImplementedWindows on Windows

        func (*Context) SetThreadSchedPolicy

        func (ctx *Context) SetThreadSchedPolicy(n int) error

        Sets the scheduling policy for internal context’s thread pool.

        This option requires ZeroMQ version 4.1, and is not available on Windows.

        Supported values for this option can be found in sched.h file, or at http://man7.org/linux/man-pages/man2/sched_setscheduler.2.html

        This option only applies before creating any sockets on the context.

        Default value: -1

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        Returns ErrorNotImplementedWindows on Windows

        func (*Context) Term

        func (ctx *Context) Term() error

        Terminates the context.

        For linger behavior, see: http://api.zeromq.org/4-1:zmq-ctx-term

        type Errno

        An Errno is an unsigned number describing an error condition as returned by a call to ZeroMQ. It implements the error interface. The number is either a standard system error, or an error defined by the C library of ZeroMQ.

        type Errno uintptr

        func AsErrno

        func AsErrno(err error) Errno

        Convert error to Errno.

        Example usage:

        switch AsErrno(err) {
        
        case zmq.Errno(syscall.EINTR):
            // standard system error
        
            // call was interrupted
        
        case zmq.ETERM:
            // error defined by ZeroMQ
        
            // context was terminated
        
        }
        

        See also: examples/interrupt.go

        func (Errno) Error

        func (errno Errno) Error() string

        Return Errno as string.

        type Event

        Used by (*Socket)Monitor() and (*Socket)RecvEvent()

        type Event int

        func (Event) String

        func (e Event) String() string

        Socket event as string.

        type Flag

        Used by (*Socket)Send() and (*Socket)Recv()

        type Flag int

        func (Flag) String

        func (f Flag) String() string

        Socket flag as string.

        type Mechanism

        Specifies the security mechanism, used by (*Socket)GetMechanism()

        type Mechanism int

        func (Mechanism) String

        func (m Mechanism) String() string

        Security mechanism as string.

        type Polled

        Return type for (*Poller)Poll

        type Polled struct {
            Socket *Socket // socket with matched event(s)
            Events State   // actual matched event(s)
        }
        

        type Poller

        type Poller struct {
            // contains filtered or unexported fields
        }
        

        func NewPoller

        func NewPoller() *Poller

        Create a new Poller

        func (*Poller) Add

        func (p *Poller) Add(soc *Socket, events State) int

        Add items to the poller

        Events is a bitwise OR of zmq.POLLIN and zmq.POLLOUT

        Returns the id of the item, which can be used as a handle to (*Poller)Update and as an index into the result of (*Poller)PollAll

        func (*Poller) Poll

        func (p *Poller) Poll(timeout time.Duration) ([]Polled, error)

        Input/output multiplexing

        If timeout < 0, wait forever until a matching event is detected

        Only sockets with matching socket events are returned in the list.

        Example:

        poller := zmq.NewPoller()
        poller.Add(socket0, zmq.POLLIN)
        poller.Add(socket1, zmq.POLLIN)
        //  Process messages from both sockets
        for {
            sockets, _ := poller.Poll(-1)
            for _, socket := range sockets {
                switch s := socket.Socket; s {
                case socket0:
                    msg, _ := s.Recv(0)
                    //  Process msg
                case socket1:
                    msg, _ := s.Recv(0)
                    //  Process msg
                }
            }
        }
        

        func (*Poller) PollAll

        func (p *Poller) PollAll(timeout time.Duration) ([]Polled, error)

        This is like (*Poller)Poll, but it returns a list of all sockets, in the same order as they were added to the poller, not just those sockets that had an event.

        For each socket in the list, you have to check the Events field to see if there was actually an event.

        When error is not nil, the return list contains no sockets.

        func (*Poller) Remove

        func (p *Poller) Remove(id int) error

        Remove a socket from the poller

        Returns ErrorNoSocket if the id was out of range

        func (*Poller) RemoveBySocket

        func (p *Poller) RemoveBySocket(soc *Socket) error

        Remove a socket from the poller

        Returns ErrorNoSocket if the socket didn't match

        func (*Poller) String

        func (p *Poller) String() string

        Poller as string.

        func (*Poller) Update

        func (p *Poller) Update(id int, events State) (previous State, err error)

        Update the events mask of a socket in the poller

        Replaces the Poller's bitmask for the specified id with the events parameter passed

        Returns the previous value, or ErrorNoSocket if the id was out of range

        func (*Poller) UpdateBySocket

        func (p *Poller) UpdateBySocket(soc *Socket, events State) (previous State, err error)

        Update the events mask of a socket in the poller

        Replaces the Poller's bitmask for the specified socket with the events parameter passed

        Returns the previous value, or ErrorNoSocket if the socket didn't match

        type Reactor

        type Reactor struct {
            // contains filtered or unexported fields
        }
        

        func NewReactor

        func NewReactor() *Reactor

        Create a reactor to mix the handling of sockets and channels (timers or other channels).

        Example:

        reactor := zmq.NewReactor()
        reactor.AddSocket(socket1, zmq.POLLIN, socket1_handler)
        reactor.AddSocket(socket2, zmq.POLLIN, socket2_handler)
        reactor.AddChannelTime(time.Tick(time.Second), 1, ticker_handler)
        reactor.Run(time.Second)
        

        Warning:

        There are problems with the reactor showing up with Go 1.14 (and later) such as data race occurrences and code lock-up. Using SetRetryAfterEINTR seems an effective fix, but at the moment there is no guaranty.

        func (*Reactor) AddChannel

        func (r *Reactor) AddChannel(ch <-chan interface{}, limit int, handler func(interface{}) error) (id uint64)

        Add channel handler to the reactor.

        Returns id of added handler, that can be used later to remove it.

        If limit is positive, at most this many items will be handled in each run through the main loop, otherwise it will process as many items as possible.

        The handler function receives the value received from the channel.

        func (*Reactor) AddChannelTime

        func (r *Reactor) AddChannelTime(ch <-chan time.Time, limit int, handler func(interface{}) error) (id uint64)

        This function wraps AddChannel, using a channel of type time.Time instead of type interface{}.

        func (*Reactor) AddSocket

        func (r *Reactor) AddSocket(soc *Socket, events State, handler func(State) error)

        Add socket handler to the reactor.

        You can have only one handler per socket. Adding a second one will remove the first.

        The handler receives the socket state as an argument: POLLIN, POLLOUT, or both.

        func (*Reactor) RemoveChannel

        func (r *Reactor) RemoveChannel(id uint64)

        Remove a channel from the reactor.

        Closed channels are removed automatically.

        func (*Reactor) RemoveSocket

        func (r *Reactor) RemoveSocket(soc *Socket)

        Remove a socket handler from the reactor.

        func (*Reactor) Run

        func (r *Reactor) Run(interval time.Duration) (err error)

        Run the reactor.

        The interval determines the time-out on the polling of sockets. Interval must be positive if there are channels. If there are no channels, you can set interval to -1.

        The run alternates between polling/handling sockets (using the interval as timeout), and reading/handling channels. The reading of channels is without time-out: if there is no activity on any channel, the run continues to poll sockets immediately.

        The run exits when any handler returns an error, returning that same error.

        func (*Reactor) SetVerbose

        func (r *Reactor) SetVerbose(verbose bool)

        type Socket

        Socket functions starting with `Set` or `Get` are used for setting and getting socket options.

        type Socket struct {
            // contains filtered or unexported fields
        }
        

        func NewSocket

        func NewSocket(t Type) (soc *Socket, err error)

        Create 0MQ socket in the default context.

        WARNING: The Socket is not thread safe. This means that you cannot access the same Socket from different goroutines without using something like a mutex.

        For a description of socket types, see: http://api.zeromq.org/4-1:zmq-socket#toc3

        func (*Socket) Bind

        func (soc *Socket) Bind(endpoint string) error

        Accept incoming connections on a socket.

        For a description of endpoint, see: http://api.zeromq.org/4-1:zmq-bind#toc2

        func (*Socket) ClientAuthCurve

        func (client *Socket) ClientAuthCurve(server_public_key, client_public_key, client_secret_key string) error

        Set CURVE client role.

        func (*Socket) ClientAuthPlain

        func (client *Socket) ClientAuthPlain(username, password string) error

        Set PLAIN client role.

        func (*Socket) Close

        func (soc *Socket) Close() error

        If not called explicitly, the socket will be closed on garbage collection

        func (*Socket) Connect

        func (soc *Socket) Connect(endpoint string) error

        Create outgoing connection from socket.

        For a description of endpoint, see: http://api.zeromq.org/4-1:zmq-connect#toc2

        func (*Socket) Context

        func (soc *Socket) Context() (*Context, error)

        Return the context associated with a socket

        func (*Socket) Disconnect

        func (soc *Socket) Disconnect(endpoint string) error

        Disconnect a socket.

        For a description of endpoint, see: http://api.zeromq.org/4-1:zmq-disconnect#toc2

        func (*Socket) GetAffinity

        func (soc *Socket) GetAffinity() (uint64, error)

        ZMQ_AFFINITY: Retrieve I/O thread affinity

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc3

        func (*Socket) GetBacklog

        func (soc *Socket) GetBacklog() (int, error)

        ZMQ_BACKLOG: Retrieve maximum length of the queue of outstanding connections

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc4

        func (*Socket) GetConnectTimeout

        func (soc *Socket) GetConnectTimeout() (time.Duration, error)

        ZMQ_CONNECT_TIMEOUT: Retrieve connect() timeout

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-getsockopt#toc5

        func (*Socket) GetCurvePublickeyRaw

        func (soc *Socket) GetCurvePublickeyRaw() (string, error)

        ZMQ_CURVE_PUBLICKEY: Retrieve current CURVE public key

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc5

        func (*Socket) GetCurvePublickeykeyZ85

        func (soc *Socket) GetCurvePublickeykeyZ85() (string, error)

        ZMQ_CURVE_PUBLICKEY: Retrieve current CURVE public key

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc5

        func (*Socket) GetCurveSecretkeyRaw

        func (soc *Socket) GetCurveSecretkeyRaw() (string, error)

        ZMQ_CURVE_SECRETKEY: Retrieve current CURVE secret key

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc6

        func (*Socket) GetCurveSecretkeyZ85

        func (soc *Socket) GetCurveSecretkeyZ85() (string, error)

        ZMQ_CURVE_SECRETKEY: Retrieve current CURVE secret key

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc6

        func (*Socket) GetCurveServerkeyRaw

        func (soc *Socket) GetCurveServerkeyRaw() (string, error)

        ZMQ_CURVE_SERVERKEY: Retrieve current CURVE server key

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc7

        func (*Socket) GetCurveServerkeyZ85

        func (soc *Socket) GetCurveServerkeyZ85() (string, error)

        ZMQ_CURVE_SERVERKEY: Retrieve current CURVE server key

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc7

        func (*Socket) GetEvents

        func (soc *Socket) GetEvents() (State, error)

        ZMQ_EVENTS: Retrieve socket event state

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc8

        func (*Socket) GetFd

        func (soc *Socket) GetFd() (int, error)

        ZMQ_FD: Retrieve file descriptor associated with the socket

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc9

        func (*Socket) GetGssapiPlaintext

        func (soc *Socket) GetGssapiPlaintext() (bool, error)

        ZMQ_GSSAPI_PLAINTEXT: Retrieve GSSAPI plaintext or encrypted status

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc10

        func (*Socket) GetGssapiPrincipal

        func (soc *Socket) GetGssapiPrincipal() (string, error)

        ZMQ_GSSAPI_PRINCIPAL: Retrieve the name of the GSSAPI principal

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc11

        func (*Socket) GetGssapiServer

        func (soc *Socket) GetGssapiServer() (bool, error)

        ZMQ_GSSAPI_SERVER: Retrieve current GSSAPI server role

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc12

        func (*Socket) GetGssapiServicePrincipal

        func (soc *Socket) GetGssapiServicePrincipal() (string, error)

        ZMQ_GSSAPI_SERVICE_PRINCIPAL: Retrieve the name of the GSSAPI service principal

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc13

        func (*Socket) GetHandshakeIvl

        func (soc *Socket) GetHandshakeIvl() (time.Duration, error)

        ZMQ_HANDSHAKE_IVL: Retrieve maximum handshake interval

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc14

        func (*Socket) GetIdentity

        func (soc *Socket) GetIdentity() (string, error)

        ZMQ_IDENTITY: Retrieve socket identity

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc15

        func (*Socket) GetImmediate

        func (soc *Socket) GetImmediate() (bool, error)

        ZMQ_IMMEDIATE: Retrieve attach-on-connect value

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc16

        func (*Socket) GetInvertMatching

        func (soc *Socket) GetInvertMatching() (int, error)

        ZMQ_INVERT_MATCHING: Retrieve inverted filtering status

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-getsockopt#toc18

        func (*Socket) GetIpv6

        func (soc *Socket) GetIpv6() (bool, error)

        ZMQ_IPV6: Retrieve IPv6 socket status

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc18

        func (*Socket) GetLastEndpoint

        func (soc *Socket) GetLastEndpoint() (string, error)

        ZMQ_LAST_ENDPOINT: Retrieve the last endpoint set

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc19

        func (*Socket) GetLinger

        func (soc *Socket) GetLinger() (time.Duration, error)

        ZMQ_LINGER: Retrieve linger period for socket shutdown

        Returns time.Duration(-1) for infinite

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc20

        func (*Socket) GetMaxmsgsize

        func (soc *Socket) GetMaxmsgsize() (int64, error)

        ZMQ_MAXMSGSIZE: Maximum acceptable inbound message size

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc21

        func (*Socket) GetMechanism

        func (soc *Socket) GetMechanism() (Mechanism, error)

        ZMQ_MECHANISM: Retrieve current security mechanism

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc22

        func (*Socket) GetMulticastHops

        func (soc *Socket) GetMulticastHops() (int, error)

        ZMQ_MULTICAST_HOPS: Maximum network hops for multicast packets

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc23

        func (*Socket) GetMulticastMaxtpdu

        func (soc *Socket) GetMulticastMaxtpdu() (int, error)

        ZMQ_MULTICAST_MAXTPDU: Maximum transport data unit size for multicast packets

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-getsockopt#toc26

        func (*Socket) GetPlainPassword

        func (soc *Socket) GetPlainPassword() (string, error)

        ZMQ_PLAIN_PASSWORD: Retrieve current password

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc24

        func (*Socket) GetPlainServer

        func (soc *Socket) GetPlainServer() (int, error)

        ZMQ_PLAIN_SERVER: Retrieve current PLAIN server role

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc25

        func (*Socket) GetPlainUsername

        func (soc *Socket) GetPlainUsername() (string, error)

        ZMQ_PLAIN_USERNAME: Retrieve current PLAIN username

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc26

        func (*Socket) GetRate

        func (soc *Socket) GetRate() (int, error)

        ZMQ_RATE: Retrieve multicast data rate

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc27

        func (*Socket) GetRcvbuf

        func (soc *Socket) GetRcvbuf() (int, error)

        ZMQ_RCVBUF: Retrieve kernel receive buffer size

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc28

        func (*Socket) GetRcvhwm

        func (soc *Socket) GetRcvhwm() (int, error)

        ZMQ_RCVHWM: Retrieve high water mark for inbound messages

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc29

        func (*Socket) GetRcvmore

        func (soc *Socket) GetRcvmore() (bool, error)

        ZMQ_RCVMORE: More message data parts to follow

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc30

        func (*Socket) GetRcvtimeo

        func (soc *Socket) GetRcvtimeo() (time.Duration, error)

        ZMQ_RCVTIMEO: Maximum time before a socket operation returns with EAGAIN

        Returns time.Duration(-1) for infinite

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc31

        func (*Socket) GetReconnectIvl

        func (soc *Socket) GetReconnectIvl() (time.Duration, error)

        ZMQ_RECONNECT_IVL: Retrieve reconnection interval

        Returns time.Duration(-1) for no reconnection

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc32

        func (*Socket) GetReconnectIvlMax

        func (soc *Socket) GetReconnectIvlMax() (time.Duration, error)

        ZMQ_RECONNECT_IVL_MAX: Retrieve maximum reconnection interval

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc33

        func (*Socket) GetRecoveryIvl

        func (soc *Socket) GetRecoveryIvl() (time.Duration, error)

        ZMQ_RECOVERY_IVL: Get multicast recovery interval

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc34

        func (*Socket) GetSndbuf

        func (soc *Socket) GetSndbuf() (int, error)

        ZMQ_SNDBUF: Retrieve kernel transmit buffer size

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc35

        func (*Socket) GetSndhwm

        func (soc *Socket) GetSndhwm() (int, error)

        ZMQ_SNDHWM: Retrieves high water mark for outbound messages

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc36

        func (*Socket) GetSndtimeo

        func (soc *Socket) GetSndtimeo() (time.Duration, error)

        ZMQ_SNDTIMEO: Maximum time before a socket operation returns with EAGAIN

        Returns time.Duration(-1) for infinite

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc37

        func (*Socket) GetSocksProxy

        func (soc *Socket) GetSocksProxy() (string, error)

        ZMQ_SOCKS_PROXY: NOT DOCUMENTED

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        func (*Socket) GetTcpKeepalive

        func (soc *Socket) GetTcpKeepalive() (int, error)

        ZMQ_TCP_KEEPALIVE: Override SO_KEEPALIVE socket option

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc38

        func (*Socket) GetTcpKeepaliveCnt

        func (soc *Socket) GetTcpKeepaliveCnt() (int, error)

        ZMQ_TCP_KEEPALIVE_CNT: Override TCP_KEEPCNT socket option

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc39

        func (*Socket) GetTcpKeepaliveIdle

        func (soc *Socket) GetTcpKeepaliveIdle() (int, error)

        ZMQ_TCP_KEEPALIVE_IDLE: Override TCP_KEEPCNT(or TCP_KEEPALIVE on some OS)

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc40

        func (*Socket) GetTcpKeepaliveIntvl

        func (soc *Socket) GetTcpKeepaliveIntvl() (int, error)

        ZMQ_TCP_KEEPALIVE_INTVL: Override TCP_KEEPINTVL socket option

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc41

        func (*Socket) GetTcpMaxrt

        func (soc *Socket) GetTcpMaxrt() (time.Duration, error)

        ZMQ_TCP_MAXRT: Retrieve Max TCP Retransmit Timeout

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-getsockopt#toc44

        func (*Socket) GetThreadSafe

        func (soc *Socket) GetThreadSafe() (bool, error)

        ZMQ_THREAD_SAFE: Retrieve socket thread safety

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-getsockopt#toc45

        func (*Socket) GetTos

        func (soc *Socket) GetTos() (int, error)

        ZMQ_TOS: Retrieve the Type-of-Service socket override status

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc42

        func (*Socket) GetType

        func (soc *Socket) GetType() (Type, error)

        ZMQ_TYPE: Retrieve socket type

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc43

        func (*Socket) GetVmciBufferMaxSize

        func (soc *Socket) GetVmciBufferMaxSize() (uint64, error)

        ZMQ_VMCI_BUFFER_MAX_SIZE: Retrieve max buffer size of the VMCI socket

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-getsockopt#toc51

        func (*Socket) GetVmciBufferMinSize

        func (soc *Socket) GetVmciBufferMinSize() (uint64, error)

        ZMQ_VMCI_BUFFER_MIN_SIZE: Retrieve min buffer size of the VMCI socket

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-getsockopt#toc50

        func (*Socket) GetVmciBufferSize

        func (soc *Socket) GetVmciBufferSize() (uint64, error)

        ZMQ_VMCI_BUFFER_SIZE: Retrieve buffer size of the VMCI socket

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-getsockopt#toc49

        func (*Socket) GetVmciConnectTimeout

        func (soc *Socket) GetVmciConnectTimeout() (time.Duration, error)

        ZMQ_VMCI_CONNECT_TIMEOUT: Retrieve connection timeout of the VMCI socket

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-getsockopt#toc52

        func (*Socket) GetZapDomain

        func (soc *Socket) GetZapDomain() (string, error)

        ZMQ_ZAP_DOMAIN: Retrieve RFC 27 authentication domain

        See: http://api.zeromq.org/4-1:zmq-getsockopt#toc44

        func (*Socket) Getusefd

        func (soc *Socket) Getusefd() (int, error)

        ZMQ_USE_FD: Retrieve the pre-allocated socket file descriptor

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-getsockopt#toc29

        func (*Socket) Monitor

        func (soc *Socket) Monitor(addr string, events Event) error

        Register a monitoring callback.

        See: http://api.zeromq.org/4-1:zmq-socket-monitor#toc2

        WARNING: Closing a context with a monitoring callback will lead to random crashes. This is a bug in the ZeroMQ library. The monitoring callback has the same context as the socket it was created for.

        Example:

        package main
        
        import (
            zmq "github.com/pebbe/zmq4"
            "log"
            "time"
        )
        
        func rep_socket_monitor(addr string) {
            s, err := zmq.NewSocket(zmq.PAIR)
            if err != nil {
                log.Fatalln(err)
            }
            err = s.Connect(addr)
            if err != nil {
                log.Fatalln(err)
            }
            for {
                a, b, c, err := s.RecvEvent(0)
                if err != nil {
                    log.Println(err)
                    break
                }
                log.Println(a, b, c)
            }
            s.Close()
        }
        
        func main() {
        
            // REP socket
            rep, err := zmq.NewSocket(zmq.REP)
            if err != nil {
                log.Fatalln(err)
            }
        
            // REP socket monitor, all events
            err = rep.Monitor("inproc://monitor.rep", zmq.EVENT_ALL)
            if err != nil {
                log.Fatalln(err)
            }
            go rep_socket_monitor("inproc://monitor.rep")
        
            // Generate an event
            rep.Bind("tcp://*:5555")
            if err != nil {
                log.Fatalln(err)
            }
        
            // Allow some time for event detection
            time.Sleep(time.Second)
        
            rep.Close()
            zmq.Term()
        }
        

        func (*Socket) Recv

        func (soc *Socket) Recv(flags Flag) (string, error)

        Receive a message part from a socket.

        For a description of flags, see: http://api.zeromq.org/4-1:zmq-msg-recv#toc2

        func (*Socket) RecvBytes

        func (soc *Socket) RecvBytes(flags Flag) ([]byte, error)

        Receive a message part from a socket.

        For a description of flags, see: http://api.zeromq.org/4-1:zmq-msg-recv#toc2

        func (*Socket) RecvBytesWithMetadata

        func (soc *Socket) RecvBytesWithMetadata(flags Flag, properties ...string) (msg []byte, metadata map[string]string, err error)

        Receive a message part with metadata.

        This requires ZeroMQ version 4.1.0. Lower versions will return the message part without metadata.

        The returned metadata map contains only those properties that exist on the message.

        For a description of flags, see: http://api.zeromq.org/4-1:zmq-msg-recv#toc2

        For a description of metadata, see: http://api.zeromq.org/4-1:zmq-msg-gets#toc3

        func (*Socket) RecvEvent

        func (soc *Socket) RecvEvent(flags Flag) (event_type Event, addr string, value int, err error)

        Receive a message part from a socket interpreted as an event.

        For a description of flags, see: http://api.zeromq.org/4-1:zmq-msg-recv#toc2

        For a description of event_type, see: http://api.zeromq.org/4-1:zmq-socket-monitor#toc3

        For an example, see: func (*Socket) Monitor

        func (*Socket) RecvMessage

        func (soc *Socket) RecvMessage(flags Flag) (msg []string, err error)

        Receive parts as message from socket.

        Returns last non-nil error code.

        func (*Socket) RecvMessageBytes

        func (soc *Socket) RecvMessageBytes(flags Flag) (msg [][]byte, err error)

        Receive parts as message from socket.

        Returns last non-nil error code.

        func (*Socket) RecvMessageBytesWithMetadata

        func (soc *Socket) RecvMessageBytesWithMetadata(flags Flag, properties ...string) (msg [][]byte, metadata map[string]string, err error)

        Receive parts as message from socket, including metadata.

        Metadata is picked from the first message part.

        For details about metadata, see RecvBytesWithMetadata().

        Returns last non-nil error code.

        func (*Socket) RecvMessageWithMetadata

        func (soc *Socket) RecvMessageWithMetadata(flags Flag, properties ...string) (msg []string, metadata map[string]string, err error)

        Receive parts as message from socket, including metadata.

        Metadata is picked from the first message part.

        For details about metadata, see RecvWithMetadata().

        Returns last non-nil error code.

        func (*Socket) RecvWithMetadata

        func (soc *Socket) RecvWithMetadata(flags Flag, properties ...string) (msg string, metadata map[string]string, err error)

        Receive a message part with metadata.

        This requires ZeroMQ version 4.1.0. Lower versions will return the message part without metadata.

        The returned metadata map contains only those properties that exist on the message.

        For a description of flags, see: http://api.zeromq.org/4-1:zmq-msg-recv#toc2

        For a description of metadata, see: http://api.zeromq.org/4-1:zmq-msg-gets#toc3

        func (*Socket) Send

        func (soc *Socket) Send(data string, flags Flag) (int, error)

        Send a message part on a socket.

        For a description of flags, see: http://api.zeromq.org/4-1:zmq-send#toc2

        func (*Socket) SendBytes

        func (soc *Socket) SendBytes(data []byte, flags Flag) (int, error)

        Send a message part on a socket.

        For a description of flags, see: http://api.zeromq.org/4-1:zmq-send#toc2

        func (*Socket) SendMessage

        func (soc *Socket) SendMessage(parts ...interface{}) (total int, err error)

        Send multi-part message on socket.

        Any `[]string' or `[][]byte' is split into separate `string's or `[]byte's

        Any other part that isn't a `string' or `[]byte' is converted to `string' with `fmt.Sprintf("%v", part)'.

        Returns total bytes sent.

        func (*Socket) SendMessageDontwait

        func (soc *Socket) SendMessageDontwait(parts ...interface{}) (total int, err error)

        Like SendMessage(), but adding the DONTWAIT flag.

        func (*Socket) ServerAuthCurve

        func (server *Socket) ServerAuthCurve(domain, secret_key string) error

        Set CURVE server role.

        func (*Socket) ServerAuthNull

        func (server *Socket) ServerAuthNull(domain string) error

        Set NULL server role.

        func (*Socket) ServerAuthPlain

        func (server *Socket) ServerAuthPlain(domain string) error

        Set PLAIN server role.

        func (*Socket) SetAffinity

        func (soc *Socket) SetAffinity(value uint64) error

        ZMQ_AFFINITY: Set I/O thread affinity

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc3

        func (*Socket) SetBacklog

        func (soc *Socket) SetBacklog(value int) error

        ZMQ_BACKLOG: Set maximum length of the queue of outstanding connections

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc4

        func (*Socket) SetConflate

        func (soc *Socket) SetConflate(value bool) error

        ZMQ_CONFLATE: Keep only last message

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc6

        func (*Socket) SetConnectRid

        func (soc *Socket) SetConnectRid(value string) error

        ZMQ_CONNECT_RID: Assign the next outbound connection id

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc5

        func (*Socket) SetConnectTimeout

        func (soc *Socket) SetConnectTimeout(value time.Duration) error

        ZMQ_CONNECT_TIMEOUT: Set connect() timeout

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc7

        func (*Socket) SetCurvePublickey

        func (soc *Socket) SetCurvePublickey(key string) error

        ZMQ_CURVE_PUBLICKEY: Set CURVE public key

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc7

        func (*Socket) SetCurveSecretkey

        func (soc *Socket) SetCurveSecretkey(key string) error

        ZMQ_CURVE_SECRETKEY: Set CURVE secret key

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc8

        func (*Socket) SetCurveServer

        func (soc *Socket) SetCurveServer(value int) error

        ZMQ_CURVE_SERVER: Set CURVE server role

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc9

        func (*Socket) SetCurveServerkey

        func (soc *Socket) SetCurveServerkey(key string) error

        ZMQ_CURVE_SERVERKEY: Set CURVE server key

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc10

        func (*Socket) SetGssapiPlaintext

        func (soc *Socket) SetGssapiPlaintext(value bool) error

        ZMQ_GSSAPI_PLAINTEXT: Disable GSSAPI encryption

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc11

        func (*Socket) SetGssapiPrincipal

        func (soc *Socket) SetGssapiPrincipal(value string) error

        ZMQ_GSSAPI_PRINCIPAL: Set name of GSSAPI principal

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc12

        func (*Socket) SetGssapiServer

        func (soc *Socket) SetGssapiServer(value bool) error

        ZMQ_GSSAPI_SERVER: Set GSSAPI server role

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc13

        func (*Socket) SetGssapiServicePrincipal

        func (soc *Socket) SetGssapiServicePrincipal(value string) error

        ZMQ_GSSAPI_SERVICE_PRINCIPAL: Set name of GSSAPI service principal

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc14

        func (*Socket) SetHandshakeIvl

        func (soc *Socket) SetHandshakeIvl(value time.Duration) error

        ZMQ_HANDSHAKE_IVL: Set maximum handshake interval

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc15

        func (*Socket) SetHeartbeatIvl

        func (soc *Socket) SetHeartbeatIvl(value time.Duration) error

        ZMQ_HEARTBEAT_IVL: Set interval between sending ZMTP heartbeats

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc17

        func (*Socket) SetHeartbeatTimeout

        func (soc *Socket) SetHeartbeatTimeout(value time.Duration) error

        ZMQ_HEARTBEAT_TIMEOUT: Set timeout for ZMTP heartbeats

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc18

        func (*Socket) SetHeartbeatTtl

        func (soc *Socket) SetHeartbeatTtl(value time.Duration) error

        ZMQ_HEARTBEAT_TTL: Set the TTL value for ZMTP heartbeats

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc19

        func (*Socket) SetIdentity

        func (soc *Socket) SetIdentity(value string) error

        ZMQ_IDENTITY: Set socket identity

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc16

        func (*Socket) SetImmediate

        func (soc *Socket) SetImmediate(value bool) error

        ZMQ_IMMEDIATE: Queue messages only to completed connections

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc17

        func (*Socket) SetInvertMatching

        func (soc *Socket) SetInvertMatching(value int) error

        ZMQ_INVERT_MATCHING: Invert message filtering

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc22

        func (*Socket) SetIpv6

        func (soc *Socket) SetIpv6(value bool) error

        ZMQ_IPV6: Enable IPv6 on socket

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc18

        func (*Socket) SetLinger

        func (soc *Socket) SetLinger(value time.Duration) error

        ZMQ_LINGER: Set linger period for socket shutdown

        For infinite, use -1

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc19

        func (*Socket) SetMaxmsgsize

        func (soc *Socket) SetMaxmsgsize(value int64) error

        ZMQ_MAXMSGSIZE: Maximum acceptable inbound message size

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc20

        func (*Socket) SetMulticastHops

        func (soc *Socket) SetMulticastHops(value int) error

        ZMQ_MULTICAST_HOPS: Maximum network hops for multicast packets

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc21

        func (*Socket) SetMulticastMaxtpdu

        func (soc *Socket) SetMulticastMaxtpdu(value int) error

        ZMQ_MULTICAST_MAXTPDU: Maximum transport data unit size for multicast packets

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc27

        func (*Socket) SetPlainPassword

        func (soc *Socket) SetPlainPassword(password string) error

        ZMQ_PLAIN_PASSWORD: Set PLAIN security password

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc22

        func (*Socket) SetPlainServer

        func (soc *Socket) SetPlainServer(value int) error

        ZMQ_PLAIN_SERVER: Set PLAIN server role

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc23

        func (*Socket) SetPlainUsername

        func (soc *Socket) SetPlainUsername(username string) error

        ZMQ_PLAIN_USERNAME: Set PLAIN security username

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc24

        func (*Socket) SetProbeRouter

        func (soc *Socket) SetProbeRouter(value int) error

        ZMQ_PROBE_ROUTER: bootstrap connections to ROUTER sockets

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc25

        func (*Socket) SetRate

        func (soc *Socket) SetRate(value int) error

        ZMQ_RATE: Set multicast data rate

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc26

        func (*Socket) SetRcvbuf

        func (soc *Socket) SetRcvbuf(value int) error

        ZMQ_RCVBUF: Set kernel receive buffer size

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc27

        func (*Socket) SetRcvhwm

        func (soc *Socket) SetRcvhwm(value int) error

        ZMQ_RCVHWM: Set high water mark for inbound messages

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc28

        func (*Socket) SetRcvtimeo

        func (soc *Socket) SetRcvtimeo(value time.Duration) error

        ZMQ_RCVTIMEO: Maximum time before a recv operation returns with EAGAIN

        For infinite, use -1

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc29

        func (*Socket) SetReconnectIvl

        func (soc *Socket) SetReconnectIvl(value time.Duration) error

        ZMQ_RECONNECT_IVL: Set reconnection interval

        For no reconnection, use -1

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc30

        func (*Socket) SetReconnectIvlMax

        func (soc *Socket) SetReconnectIvlMax(value time.Duration) error

        ZMQ_RECONNECT_IVL_MAX: Set maximum reconnection interval

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc31

        func (*Socket) SetRecoveryIvl

        func (soc *Socket) SetRecoveryIvl(value time.Duration) error

        ZMQ_RECOVERY_IVL: Set multicast recovery interval

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc32

        func (*Socket) SetReqCorrelate

        func (soc *Socket) SetReqCorrelate(value int) error

        ZMQ_REQ_CORRELATE: match replies with requests

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc33

        func (*Socket) SetReqRelaxed

        func (soc *Socket) SetReqRelaxed(value int) error

        ZMQ_REQ_RELAXED: relax strict alternation between request and reply

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc34

        func (*Socket) SetRouterHandover

        func (soc *Socket) SetRouterHandover(value bool) error

        ZMQ_ROUTER_HANDOVER: handle duplicate client identities on ROUTER sockets

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc35

        func (*Socket) SetRouterMandatory

        func (soc *Socket) SetRouterMandatory(value int) error

        ZMQ_ROUTER_MANDATORY: accept only routable messages on ROUTER sockets

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc36

        func (*Socket) SetRouterRaw

        func (soc *Socket) SetRouterRaw(value int) error

        ZMQ_ROUTER_RAW: switch ROUTER socket to raw mode

        This option is deprecated since ZeroMQ version 4.1, please use ZMQ_STREAM sockets instead.

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc37

        func (*Socket) SetSndbuf

        func (soc *Socket) SetSndbuf(value int) error

        ZMQ_SNDBUF: Set kernel transmit buffer size

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc38

        func (*Socket) SetSndhwm

        func (soc *Socket) SetSndhwm(value int) error

        ZMQ_SNDHWM: Set high water mark for outbound messages

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc39

        func (*Socket) SetSndtimeo

        func (soc *Socket) SetSndtimeo(value time.Duration) error

        ZMQ_SNDTIMEO: Maximum time before a send operation returns with EAGAIN

        For infinite, use -1

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc40

        func (*Socket) SetSocksProxy

        func (soc *Socket) SetSocksProxy(value string) error

        ZMQ_SOCKS_PROXY: NOT DOCUMENTED

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        func (*Socket) SetStreamNotify

        func (soc *Socket) SetStreamNotify(value int) error

        ZMQ_STREAM_NOTIFY: send connect and disconnect notifications

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc48

        func (*Socket) SetSubscribe

        func (soc *Socket) SetSubscribe(filter string) error

        ZMQ_SUBSCRIBE: Establish message filter

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc41

        func (*Socket) SetTcpAcceptFilter

        func (soc *Socket) SetTcpAcceptFilter(filter string) error

        ZMQ_TCP_ACCEPT_FILTER: Assign filters to allow new TCP connections

        This option is deprecated since ZeroMQ version 4.1, please use authentication via the ZAP API and IP address whitelisting / blacklisting.

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc50

        func (*Socket) SetTcpKeepalive

        func (soc *Socket) SetTcpKeepalive(value int) error

        ZMQ_TCP_KEEPALIVE: Override SO_KEEPALIVE socket option

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc42

        func (*Socket) SetTcpKeepaliveCnt

        func (soc *Socket) SetTcpKeepaliveCnt(value int) error

        ZMQ_TCP_KEEPALIVE_CNT: Override TCP_KEEPCNT socket option

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc43

        func (*Socket) SetTcpKeepaliveIdle

        func (soc *Socket) SetTcpKeepaliveIdle(value int) error

        ZMQ_TCP_KEEPALIVE_IDLE: Override TCP_KEEPCNT(or TCP_KEEPALIVE on some OS)

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc44

        func (*Socket) SetTcpKeepaliveIntvl

        func (soc *Socket) SetTcpKeepaliveIntvl(value int) error

        ZMQ_TCP_KEEPALIVE_INTVL: Override TCP_KEEPINTVL socket option

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc45

        func (*Socket) SetTcpMaxrt

        func (soc *Socket) SetTcpMaxrt(value time.Duration) error

        ZMQ_TCP_MAXRT: Set TCP Maximum Retransmit Timeout

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc54

        func (*Socket) SetTos

        func (soc *Socket) SetTos(value int) error

        ZMQ_TOS: Set the Type-of-Service on socket

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc46

        func (*Socket) SetUnsubscribe

        func (soc *Socket) SetUnsubscribe(filter string) error

        ZMQ_UNSUBSCRIBE: Remove message filter

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc47

        func (*Socket) SetUseFd

        func (soc *Socket) SetUseFd(value int) error

        ZMQ_USE_FD: Set the pre-allocated socket file descriptor

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc31

        func (*Socket) SetVmciBufferMaxSize

        func (soc *Socket) SetVmciBufferMaxSize(value uint64) error

        ZMQ_VMCI_BUFFER_MAX_SIZE: Set max buffer size of the VMCI socket

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc70

        func (*Socket) SetVmciBufferMinSize

        func (soc *Socket) SetVmciBufferMinSize(value uint64) error

        ZMQ_VMCI_BUFFER_MIN_SIZE: Set min buffer size of the VMCI socket

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc69

        func (*Socket) SetVmciBufferSize

        func (soc *Socket) SetVmciBufferSize(value uint64) error

        ZMQ_VMCI_BUFFER_SIZE: Set buffer size of the VMCI socket

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc68

        func (*Socket) SetVmciConnectTimeout

        func (soc *Socket) SetVmciConnectTimeout(value time.Duration) error

        ZMQ_VMCI_CONNECT_TIMEOUT: Set connection timeout of the VMCI socket

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc71

        func (*Socket) SetXpubManual

        func (soc *Socket) SetXpubManual(value int) error

        ZMQ_XPUB_MANUAL: change the subscription handling to manual

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc59

        func (*Socket) SetXpubNodrop

        func (soc *Socket) SetXpubNodrop(value bool) error

        ZMQ_XPUB_NODROP: do not silently drop messages if SENDHWM is reached

        Returns ErrorNotImplemented41 with ZeroMQ version < 4.1

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc60

        func (*Socket) SetXpubVerbose

        func (soc *Socket) SetXpubVerbose(value int) error

        ZMQ_XPUB_VERBOSE: provide all subscription messages on XPUB sockets

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc48

        func (*Socket) SetXpubVerboser

        func (soc *Socket) SetXpubVerboser(value int) error

        ZMQ_XPUB_VERBOSER: pass subscribe and unsubscribe messages on XPUB socket

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc58

        func (*Socket) SetXpubWelcomeMsg

        func (soc *Socket) SetXpubWelcomeMsg(value string) error

        ZMQ_XPUB_WELCOME_MSG: set welcome message that will be received by subscriber when connecting

        Returns ErrorNotImplemented42 with ZeroMQ version < 4.2

        See: http://api.zeromq.org/4-2:zmq-setsockopt#toc61

        func (*Socket) SetZapDomain

        func (soc *Socket) SetZapDomain(domain string) error

        ZMQ_ZAP_DOMAIN: Set RFC 27 authentication domain

        See: http://api.zeromq.org/4-1:zmq-setsockopt#toc49

        func (Socket) String

        func (soc Socket) String() string

        Socket as string.

        func (*Socket) Unbind

        func (soc *Socket) Unbind(endpoint string) error

        Stop accepting connections on a socket.

        For a description of endpoint, see: http://api.zeromq.org/4-1:zmq-unbind#toc2

        type State

        Used by (soc *Socket)GetEvents()

        type State int

        func (State) String

        func (s State) String() string

        Socket state as string.

        type Type

        Specifies the type of a socket, used by NewSocket()

        type Type int

        func (Type) String

        func (t Type) String() string

        Socket type as string.

        Subdirectories

        Name Synopsis
        ..
        draft A Go interface to ZeroMQ (zmq, 0mq) version 4.
        examples_security
        log - Go Documentation Server
        ...

        Package log

        Overview ▾

        Package log implements a simple logging package. It defines a type, Logger, with methods for formatting output. It also has a predefined 'standard' Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and Panic[f|ln], which are easier to use than creating a Logger manually. That logger writes to standard error and prints the date and time of each logged message. Every log message is output on a separate line: if the message being printed does not end in a newline, the logger will add one. The Fatal functions call os.Exit(1) after writing the log message. The Panic functions call panic after writing the log message.

        Constants

        These flags define which text to prefix to each log entry generated by the Logger. Bits are or'ed together to control what's printed. With the exception of the Lmsgprefix flag, there is no control over the order they appear (the order listed here) or the format they present (as described in the comments). The prefix is followed by a colon only when Llongfile or Lshortfile is specified. For example, flags Ldate | Ltime (or LstdFlags) produce,

        2009/01/23 01:23:23 message
        

        while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,

        2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
        
        const (
            Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
            Ltime                         // the time in the local time zone: 01:23:23
            Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
            Llongfile                     // full file name and line number: /a/b/c/d.go:23
            Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
            LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
            Lmsgprefix                    // move the "prefix" from the beginning of the line to before the message
            LstdFlags     = Ldate | Ltime // initial values for the standard logger
        )

        func Fatal

        func Fatal(v ...any)

        Fatal is equivalent to Print followed by a call to os.Exit(1).

        func Fatalf

        func Fatalf(format string, v ...any)

        Fatalf is equivalent to Printf followed by a call to os.Exit(1).

        func Fatalln

        func Fatalln(v ...any)

        Fatalln is equivalent to Println followed by a call to os.Exit(1).

        func Flags

        func Flags() int

        Flags returns the output flags for the standard logger. The flag bits are Ldate, Ltime, and so on.

        func Output

        func Output(calldepth int, s string) error

        Output writes the output for a logging event. The string s contains the text to print after the prefix specified by the flags of the Logger. A newline is appended if the last character of s is not already a newline. Calldepth is the count of the number of frames to skip when computing the file name and line number if Llongfile or Lshortfile is set; a value of 1 will print the details for the caller of Output.

        func Panic

        func Panic(v ...any)

        Panic is equivalent to Print followed by a call to panic().

        func Panicf

        func Panicf(format string, v ...any)

        Panicf is equivalent to Printf followed by a call to panic().

        func Panicln

        func Panicln(v ...any)

        Panicln is equivalent to Println followed by a call to panic().

        func Prefix

        func Prefix() string

        Prefix returns the output prefix for the standard logger.

        func Print

        func Print(v ...any)

        Print calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Print.

        func Printf

        func Printf(format string, v ...any)

        Printf calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Printf.

        func Println

        func Println(v ...any)

        Println calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Println.

        func SetFlags

        func SetFlags(flag int)

        SetFlags sets the output flags for the standard logger. The flag bits are Ldate, Ltime, and so on.

        func SetOutput

        func SetOutput(w io.Writer)

        SetOutput sets the output destination for the standard logger.

        func SetPrefix

        func SetPrefix(prefix string)

        SetPrefix sets the output prefix for the standard logger.

        func Writer

        func Writer() io.Writer

        Writer returns the output destination for the standard logger.

        type Logger

        A Logger represents an active logging object that generates lines of output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer.

        type Logger struct {
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        var (
            buf    bytes.Buffer
            logger = log.New(&buf, "logger: ", log.Lshortfile)
        )
        
        logger.Print("Hello, log file!")
        
        fmt.Print(&buf)
        

        Output:

        logger: example_test.go:19: Hello, log file!
        

        func Default

        func Default() *Logger

        Default returns the standard logger used by the package-level output functions.

        func New

        func New(out io.Writer, prefix string, flag int) *Logger

        New creates a new Logger. The out variable sets the destination to which log data will be written. The prefix appears at the beginning of each generated log line, or after the log header if the Lmsgprefix flag is provided. The flag argument defines the logging properties.

        func (*Logger) Fatal

        func (l *Logger) Fatal(v ...any)

        Fatal is equivalent to l.Print() followed by a call to os.Exit(1).

        func (*Logger) Fatalf

        func (l *Logger) Fatalf(format string, v ...any)

        Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1).

        func (*Logger) Fatalln

        func (l *Logger) Fatalln(v ...any)

        Fatalln is equivalent to l.Println() followed by a call to os.Exit(1).

        func (*Logger) Flags

        func (l *Logger) Flags() int

        Flags returns the output flags for the logger. The flag bits are Ldate, Ltime, and so on.

        func (*Logger) Output

        func (l *Logger) Output(calldepth int, s string) error

        Output writes the output for a logging event. The string s contains the text to print after the prefix specified by the flags of the Logger. A newline is appended if the last character of s is not already a newline. Calldepth is used to recover the PC and is provided for generality, although at the moment on all pre-defined paths it will be 2.

        Example

        Code:

        var (
            buf    bytes.Buffer
            logger = log.New(&buf, "INFO: ", log.Lshortfile)
        
            infof = func(info string) {
                logger.Output(2, info)
            }
        )
        
        infof("Hello world")
        
        fmt.Print(&buf)
        

        Output:

        INFO: example_test.go:36: Hello world
        

        func (*Logger) Panic

        func (l *Logger) Panic(v ...any)

        Panic is equivalent to l.Print() followed by a call to panic().

        func (*Logger) Panicf

        func (l *Logger) Panicf(format string, v ...any)

        Panicf is equivalent to l.Printf() followed by a call to panic().

        func (*Logger) Panicln

        func (l *Logger) Panicln(v ...any)

        Panicln is equivalent to l.Println() followed by a call to panic().

        func (*Logger) Prefix

        func (l *Logger) Prefix() string

        Prefix returns the output prefix for the logger.

        func (*Logger) Print

        func (l *Logger) Print(v ...any)

        Print calls l.Output to print to the logger. Arguments are handled in the manner of fmt.Print.

        func (*Logger) Printf

        func (l *Logger) Printf(format string, v ...any)

        Printf calls l.Output to print to the logger. Arguments are handled in the manner of fmt.Printf.

        func (*Logger) Println

        func (l *Logger) Println(v ...any)

        Println calls l.Output to print to the logger. Arguments are handled in the manner of fmt.Println.

        func (*Logger) SetFlags

        func (l *Logger) SetFlags(flag int)

        SetFlags sets the output flags for the logger. The flag bits are Ldate, Ltime, and so on.

        func (*Logger) SetOutput

        func (l *Logger) SetOutput(w io.Writer)

        SetOutput sets the output destination for the logger.

        func (*Logger) SetPrefix

        func (l *Logger) SetPrefix(prefix string)

        SetPrefix sets the output prefix for the logger.

        func (*Logger) Writer

        func (l *Logger) Writer() io.Writer

        Writer returns the output destination for the logger.

        Subdirectories

        Name Synopsis
        ..
        slog Package slog provides structured logging, in which log records include a message, a severity level, and various other attributes expressed as key-value pairs.
        syslog Package syslog provides a simple interface to the system log service.
        src/goberkeley/berkeley/anode.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/anode.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"errors"
             5  	"log"
             6  	"time"
             7  
             8  	zmq "github.com/pebbe/zmq4" // Librería para trabajar con ZeroMQ
             9  )
            10  
            11  // Interfaz Handler con el método HandleProcess
            12  type Handler interface {
            13  	HandleProcess(message string) (string, error)
            14  }
            15  
            16  // AbstractNode proporciona la funcionalidad base para nodos en el sistema.
            17  type AbstractNode struct {
            18  	Name          string
            19  	Address       string
            20  	Timeout       time.Duration
            21  	NodeAddresses map[string]string
            22  	Context       *zmq.Context
            23  	Socket        *zmq.Socket
            24  	Logger        *log.Logger
            25  	Handler       // Composición de la interfaz Handler
            26  }
            27  
            28  // NewAbstractNode crea e inicializa un nuevo nodo base.
            29  func NewAbstractNode(name, address string, timeout time.Duration) (*AbstractNode, error) {
            30  	context, err := zmq.NewContext()
            31  	if err != nil {
            32  		return nil, errors.New("error al crear el contexto ZeroMQ")
            33  	}
            34  
            35  	return &AbstractNode{
            36  		Name:    name,
            37  		Address: address,
            38  		Timeout: timeout,
            39  		Context: context,
            40  		Logger:  log.Default(),
            41  	}, nil
            42  }
            43  
            44  // InitializeNodeWithAddresses inicializa un nodo con direcciones de otros nodos.
            45  func InitializeNodeWithAddresses(name, address string, timeout time.Duration, addresses map[string]string) (*AbstractNode, error) {
            46  	var n *AbstractNode
            47  	n, err := NewAbstractNode(name, address, timeout)
            48  	if err != nil {
            49  		return nil, err
            50  	}
            51  	n.NodeAddresses = addresses
            52  	n.Logger.Printf("Nodo %s inicializado con direcciones %v", n.Name, addresses)
            53  	return n, nil
            54  }
            55  
            56  // SendMessageSync envía un mensaje de forma síncrona y espera una respuesta.
            57  func (n *AbstractNode) SendMessageSync(address string, message string) (string, error) {
            58  	// Creación del socket REQ (Request) para enviar el mensaje
            59  	var socket *zmq.Socket
            60  	socket, err := n.Context.NewSocket(zmq.REQ)
            61  	if err != nil {
            62  		n.Logger.Printf("Error al crear el socket REQ: %v", err) // Traza adicional
            63  		return "", errors.New("error al crear el socket REQ")
            64  	}
            65  	defer socket.Close()
            66  
            67  	// Establecer el timeout para recibir respuestas
            68  	socket.SetRcvtimeo(n.Timeout * time.Millisecond) // Convertir el timeout a milisegundos
            69  
            70  	// Traza: Mostrar el valor del timeout configurado
            71  	n.Logger.Printf("Timeout de recepción configurado a: %v milisegundos", int64(n.Timeout)) // Traza para el timeout
            72  
            73  	// Conectar al socket en la dirección proporcionada
            74  	err = socket.Connect("tcp://" + address)
            75  	if err != nil {
            76  		n.Logger.Printf("Error al conectar con %s: %v", address, err) // Traza adicional
            77  		return "", errors.New("error al conectar con " + address)
            78  	}
            79  
            80  	n.Logger.Printf("Conectado a %s", address) // Traza para verificar la conexión
            81  
            82  	// Enviar el mensaje al servidor
            83  	_, err = socket.Send(message, 0)
            84  	if err != nil {
            85  		n.Logger.Printf("Error al enviar el mensaje a %s: %v", address, err) // Traza adicional
            86  		return "", errors.New("error al enviar el mensaje")
            87  	}
            88  
            89  	n.Logger.Printf("Mensaje enviado a %s: %s", address, message) // Traza de envío
            90  
            91  	// Intentar recibir la respuesta
            92  	reply, err := socket.Recv(0)
            93  	if err != nil {
            94  		n.Logger.Printf("Error al recibir respuesta de %s: %v", address, err) // Traza para el error de recepción
            95  		return "", errors.New("no se recibió respuesta del socket")
            96  	}
            97  
            98  	n.Logger.Printf("Respuesta recibida de %s: %s", address, reply) // Traza de respuesta recibida
            99  	return reply, nil
           100  }
           101  
           102  // SendMessageAsync envía un mensaje de manera asíncrona.
           103  func (n *AbstractNode) SendMessageAsync(address, message string) error {
           104  	socket, err := n.Context.NewSocket(zmq.PUSH)
           105  	if err != nil {
           106  		return errors.New("error al crear el socket PUSH")
           107  	}
           108  	defer socket.Close()
           109  
           110  	err = socket.Connect("tcp://" + address)
           111  	if err != nil {
           112  		return errors.New("error al conectar con " + address)
           113  	}
           114  
           115  	_, err = socket.Send(message, 0)
           116  	if err != nil {
           117  		return errors.New("error al enviar el mensaje")
           118  	}
           119  
           120  	n.Logger.Printf("Mensaje asincrónico enviado a %s: %s", address, message)
           121  	return nil
           122  }
           123  
           124  // StartListening inicia el proceso de escucha para mensajes entrantes en el nodo.
           125  // Configura un socket de tipo REP (Response) para recibir y responder a mensajes.
           126  func (n *AbstractNode) StartListening() error {
           127  	// Log para indicar que estamos intentando crear un socket REP.
           128  	n.Logger.Printf("Intentando crear un socket REP para el nodo %s en la dirección %s", n.Name, n.Address)
           129  	socket, err := n.Context.NewSocket(zmq.REP)
           130  	if err != nil {
           131  		// Si ocurre un error al crear el socket, loguea el error y retorna un mensaje de error.
           132  		n.Logger.Printf("Error al crear el socket REP: %v", err)
           133  		return errors.New("error al crear el socket REP")
           134  	}
           135  	n.Socket = socket
           136  	n.Logger.Printf("Socket REP creado exitosamente para el nodo %s", n.Name)
           137  
           138  	// Enlaza el socket a la dirección TCP proporcionada en el nodo para esperar conexiones.
           139  	n.Logger.Printf("Enlazando el socket REP en la dirección tcp://%s", n.Address)
           140  	err = socket.Bind("tcp://" + n.Address)
           141  	if err != nil {
           142  		// Si ocurre un error al enlazar el socket, loguea el error y retorna un mensaje de error.
           143  		n.Logger.Printf("Error al enlazar el socket en %s: %v", n.Address, err)
           144  		return errors.New("error al enlazar el socket en " + n.Address)
           145  	}
           146  	n.Logger.Printf("Socket enlazado exitosamente en %s", n.Address)
           147  
           148  	// Inicia una nueva goroutine para escuchar de manera concurrente sin bloquear el hilo principal.
           149  	n.Logger.Printf("Iniciando goroutine para escuchar en el nodo %s", n.Name)
           150  	go func() {
           151  		// Logea que el nodo ha comenzado a escuchar en la dirección configurada.
           152  		n.Logger.Printf("Nodo %s escuchando en %s", n.Name, n.Address)
           153  
           154  		// Entra en un bucle infinito para recibir y procesar mensajes.
           155  		for {
           156  			// Recibe un mensaje del socket.
           157  			n.Logger.Printf("Esperando mensaje en %s...", n.Name)
           158  			message, err := socket.Recv(0)
           159  			if err != nil {
           160  				// Si ocurre un error al recibir el mensaje, loguea el error y termina el bucle.
           161  				n.Logger.Printf("Error al recibir mensaje: %v", err)
           162  				break
           163  			}
           164  			n.Logger.Printf("Mensaje recibido en %s: %v", n.Name, message)
           165  
           166  			// Llama al método HandleProcess, que es implementado por el tipo real de nodo (Follower, Leader, etc.).
           167  			// Este método procesará el mensaje recibido y generará una respuesta.
           168  			n.Logger.Printf("Procesando mensaje en %s...", n.Name)
           169  			response, err := n.Handler.HandleProcess(message)
           170  			if err != nil {
           171  				// Si hay un error al procesar el mensaje, loguea el error y termina el bucle.
           172  				n.Logger.Printf("Error en HandleProcess en %s: %v", n.Name, err)
           173  				break
           174  			}
           175  
           176  			// Envía la respuesta de vuelta al cliente a través del socket.
           177  			n.Logger.Printf("Enviando respuesta en %s: %v", n.Name, response)
           178  			_, err = socket.Send(response, 0)
           179  			if err != nil {
           180  				// Si ocurre un error al enviar la respuesta, loguea el error y termina el bucle.
           181  				n.Logger.Printf("Error al enviar respuesta en %s: %v", n.Name, err)
           182  				break
           183  			}
           184  		}
           185  	}()
           186  
           187  	// La función regresa nil si todo se configura correctamente y la goroutine se inicia sin errores.
           188  	n.Logger.Printf("Escucha iniciada exitosamente en el nodo %s", n.Name)
           189  	return nil
           190  }
           191  
           192  // Close cierra los recursos del nodo.
           193  func (n *AbstractNode) Close() error {
           194  	if n.Socket != nil {
           195  		n.Socket.Close()
           196  		n.Logger.Printf("Socket cerrado para el nodo %s", n.Name)
           197  	}
           198  	if n.Context != nil {
           199  		n.Context.Term()
           200  		n.Logger.Printf("Contexto cerrado para el nodo %s", n.Name)
           201  	}
           202  	return nil
           203  }
           204  
           205  // handleProcess debe ser sobrescrito por las subclases para procesar mensajes.
           206  func (n *AbstractNode) handleProcess(message string) string {
           207  	n.Logger.Printf("Procesando mensaje: %s", message)
           208  	return `{"status":"unhandled"}`
           209  }
           210  
        

        View as plain text

        src/goberkeley/berkeley/anode.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/anode.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"errors"
             5  	"log"
             6  	"time"
             7  
             8  	zmq "github.com/pebbe/zmq4" // Librería para trabajar con ZeroMQ
             9  )
            10  
            11  // Interfaz Handler con el método HandleProcess
            12  type Handler interface {
            13  	HandleProcess(message string) (string, error)
            14  }
            15  
            16  // AbstractNode proporciona la funcionalidad base para nodos en el sistema.
            17  type AbstractNode struct {
            18  	Name          string
            19  	Address       string
            20  	Timeout       time.Duration
            21  	NodeAddresses map[string]string
            22  	Context       *zmq.Context
            23  	Socket        *zmq.Socket
            24  	Logger        *log.Logger
            25  	Handler       // Composición de la interfaz Handler
            26  }
            27  
            28  // NewAbstractNode crea e inicializa un nuevo nodo base.
            29  func NewAbstractNode(name, address string, timeout time.Duration) (*AbstractNode, error) {
            30  	context, err := zmq.NewContext()
            31  	if err != nil {
            32  		return nil, errors.New("error al crear el contexto ZeroMQ")
            33  	}
            34  
            35  	return &AbstractNode{
            36  		Name:    name,
            37  		Address: address,
            38  		Timeout: timeout,
            39  		Context: context,
            40  		Logger:  log.Default(),
            41  	}, nil
            42  }
            43  
            44  // InitializeNodeWithAddresses inicializa un nodo con direcciones de otros nodos.
            45  func InitializeNodeWithAddresses(name, address string, timeout time.Duration, addresses map[string]string) (*AbstractNode, error) {
            46  	var n *AbstractNode
            47  	n, err := NewAbstractNode(name, address, timeout)
            48  	if err != nil {
            49  		return nil, err
            50  	}
            51  	n.NodeAddresses = addresses
            52  	n.Logger.Printf("Nodo %s inicializado con direcciones %v", n.Name, addresses)
            53  	return n, nil
            54  }
            55  
            56  // SendMessageSync envía un mensaje de forma síncrona y espera una respuesta.
            57  func (n *AbstractNode) SendMessageSync(address string, message string) (string, error) {
            58  	// Creación del socket REQ (Request) para enviar el mensaje
            59  	var socket *zmq.Socket
            60  	socket, err := n.Context.NewSocket(zmq.REQ)
            61  	if err != nil {
            62  		n.Logger.Printf("Error al crear el socket REQ: %v", err) // Traza adicional
            63  		return "", errors.New("error al crear el socket REQ")
            64  	}
            65  	defer socket.Close()
            66  
            67  	// Establecer el timeout para recibir respuestas
            68  	socket.SetRcvtimeo(n.Timeout * time.Millisecond) // Convertir el timeout a milisegundos
            69  
            70  	// Traza: Mostrar el valor del timeout configurado
            71  	n.Logger.Printf("Timeout de recepción configurado a: %v milisegundos", int64(n.Timeout)) // Traza para el timeout
            72  
            73  	// Conectar al socket en la dirección proporcionada
            74  	err = socket.Connect("tcp://" + address)
            75  	if err != nil {
            76  		n.Logger.Printf("Error al conectar con %s: %v", address, err) // Traza adicional
            77  		return "", errors.New("error al conectar con " + address)
            78  	}
            79  
            80  	n.Logger.Printf("Conectado a %s", address) // Traza para verificar la conexión
            81  
            82  	// Enviar el mensaje al servidor
            83  	_, err = socket.Send(message, 0)
            84  	if err != nil {
            85  		n.Logger.Printf("Error al enviar el mensaje a %s: %v", address, err) // Traza adicional
            86  		return "", errors.New("error al enviar el mensaje")
            87  	}
            88  
            89  	n.Logger.Printf("Mensaje enviado a %s: %s", address, message) // Traza de envío
            90  
            91  	// Intentar recibir la respuesta
            92  	reply, err := socket.Recv(0)
            93  	if err != nil {
            94  		n.Logger.Printf("Error al recibir respuesta de %s: %v", address, err) // Traza para el error de recepción
            95  		return "", errors.New("no se recibió respuesta del socket")
            96  	}
            97  
            98  	n.Logger.Printf("Respuesta recibida de %s: %s", address, reply) // Traza de respuesta recibida
            99  	return reply, nil
           100  }
           101  
           102  // SendMessageAsync envía un mensaje de manera asíncrona.
           103  func (n *AbstractNode) SendMessageAsync(address, message string) error {
           104  	socket, err := n.Context.NewSocket(zmq.PUSH)
           105  	if err != nil {
           106  		return errors.New("error al crear el socket PUSH")
           107  	}
           108  	defer socket.Close()
           109  
           110  	err = socket.Connect("tcp://" + address)
           111  	if err != nil {
           112  		return errors.New("error al conectar con " + address)
           113  	}
           114  
           115  	_, err = socket.Send(message, 0)
           116  	if err != nil {
           117  		return errors.New("error al enviar el mensaje")
           118  	}
           119  
           120  	n.Logger.Printf("Mensaje asincrónico enviado a %s: %s", address, message)
           121  	return nil
           122  }
           123  
           124  // StartListening inicia el proceso de escucha para mensajes entrantes en el nodo.
           125  // Configura un socket de tipo REP (Response) para recibir y responder a mensajes.
           126  func (n *AbstractNode) StartListening() error {
           127  	// Log para indicar que estamos intentando crear un socket REP.
           128  	n.Logger.Printf("Intentando crear un socket REP para el nodo %s en la dirección %s", n.Name, n.Address)
           129  	socket, err := n.Context.NewSocket(zmq.REP)
           130  	if err != nil {
           131  		// Si ocurre un error al crear el socket, loguea el error y retorna un mensaje de error.
           132  		n.Logger.Printf("Error al crear el socket REP: %v", err)
           133  		return errors.New("error al crear el socket REP")
           134  	}
           135  	n.Socket = socket
           136  	n.Logger.Printf("Socket REP creado exitosamente para el nodo %s", n.Name)
           137  
           138  	// Enlaza el socket a la dirección TCP proporcionada en el nodo para esperar conexiones.
           139  	n.Logger.Printf("Enlazando el socket REP en la dirección tcp://%s", n.Address)
           140  	err = socket.Bind("tcp://" + n.Address)
           141  	if err != nil {
           142  		// Si ocurre un error al enlazar el socket, loguea el error y retorna un mensaje de error.
           143  		n.Logger.Printf("Error al enlazar el socket en %s: %v", n.Address, err)
           144  		return errors.New("error al enlazar el socket en " + n.Address)
           145  	}
           146  	n.Logger.Printf("Socket enlazado exitosamente en %s", n.Address)
           147  
           148  	// Inicia una nueva goroutine para escuchar de manera concurrente sin bloquear el hilo principal.
           149  	n.Logger.Printf("Iniciando goroutine para escuchar en el nodo %s", n.Name)
           150  	go func() {
           151  		// Logea que el nodo ha comenzado a escuchar en la dirección configurada.
           152  		n.Logger.Printf("Nodo %s escuchando en %s", n.Name, n.Address)
           153  
           154  		// Entra en un bucle infinito para recibir y procesar mensajes.
           155  		for {
           156  			// Recibe un mensaje del socket.
           157  			n.Logger.Printf("Esperando mensaje en %s...", n.Name)
           158  			message, err := socket.Recv(0)
           159  			if err != nil {
           160  				// Si ocurre un error al recibir el mensaje, loguea el error y termina el bucle.
           161  				n.Logger.Printf("Error al recibir mensaje: %v", err)
           162  				break
           163  			}
           164  			n.Logger.Printf("Mensaje recibido en %s: %v", n.Name, message)
           165  
           166  			// Llama al método HandleProcess, que es implementado por el tipo real de nodo (Follower, Leader, etc.).
           167  			// Este método procesará el mensaje recibido y generará una respuesta.
           168  			n.Logger.Printf("Procesando mensaje en %s...", n.Name)
           169  			response, err := n.Handler.HandleProcess(message)
           170  			if err != nil {
           171  				// Si hay un error al procesar el mensaje, loguea el error y termina el bucle.
           172  				n.Logger.Printf("Error en HandleProcess en %s: %v", n.Name, err)
           173  				break
           174  			}
           175  
           176  			// Envía la respuesta de vuelta al cliente a través del socket.
           177  			n.Logger.Printf("Enviando respuesta en %s: %v", n.Name, response)
           178  			_, err = socket.Send(response, 0)
           179  			if err != nil {
           180  				// Si ocurre un error al enviar la respuesta, loguea el error y termina el bucle.
           181  				n.Logger.Printf("Error al enviar respuesta en %s: %v", n.Name, err)
           182  				break
           183  			}
           184  		}
           185  	}()
           186  
           187  	// La función regresa nil si todo se configura correctamente y la goroutine se inicia sin errores.
           188  	n.Logger.Printf("Escucha iniciada exitosamente en el nodo %s", n.Name)
           189  	return nil
           190  }
           191  
           192  // Close cierra los recursos del nodo.
           193  func (n *AbstractNode) Close() error {
           194  	if n.Socket != nil {
           195  		n.Socket.Close()
           196  		n.Logger.Printf("Socket cerrado para el nodo %s", n.Name)
           197  	}
           198  	if n.Context != nil {
           199  		n.Context.Term()
           200  		n.Logger.Printf("Contexto cerrado para el nodo %s", n.Name)
           201  	}
           202  	return nil
           203  }
           204  
           205  // handleProcess debe ser sobrescrito por las subclases para procesar mensajes.
           206  func (n *AbstractNode) handleProcess(message string) string {
           207  	n.Logger.Printf("Procesando mensaje: %s", message)
           208  	return `{"status":"unhandled"}`
           209  }
           210  
        

        View as plain text

        src/goberkeley/berkeley/anode.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/anode.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"errors"
             5  	"log"
             6  	"time"
             7  
             8  	zmq "github.com/pebbe/zmq4" // Librería para trabajar con ZeroMQ
             9  )
            10  
            11  // Interfaz Handler con el método HandleProcess
            12  type Handler interface {
            13  	HandleProcess(message string) (string, error)
            14  }
            15  
            16  // AbstractNode proporciona la funcionalidad base para nodos en el sistema.
            17  type AbstractNode struct {
            18  	Name          string
            19  	Address       string
            20  	Timeout       time.Duration
            21  	NodeAddresses map[string]string
            22  	Context       *zmq.Context
            23  	Socket        *zmq.Socket
            24  	Logger        *log.Logger
            25  	Handler       // Composición de la interfaz Handler
            26  }
            27  
            28  // NewAbstractNode crea e inicializa un nuevo nodo base.
            29  func NewAbstractNode(name, address string, timeout time.Duration) (*AbstractNode, error) {
            30  	context, err := zmq.NewContext()
            31  	if err != nil {
            32  		return nil, errors.New("error al crear el contexto ZeroMQ")
            33  	}
            34  
            35  	return &AbstractNode{
            36  		Name:    name,
            37  		Address: address,
            38  		Timeout: timeout,
            39  		Context: context,
            40  		Logger:  log.Default(),
            41  	}, nil
            42  }
            43  
            44  // InitializeNodeWithAddresses inicializa un nodo con direcciones de otros nodos.
            45  func InitializeNodeWithAddresses(name, address string, timeout time.Duration, addresses map[string]string) (*AbstractNode, error) {
            46  	var n *AbstractNode
            47  	n, err := NewAbstractNode(name, address, timeout)
            48  	if err != nil {
            49  		return nil, err
            50  	}
            51  	n.NodeAddresses = addresses
            52  	n.Logger.Printf("Nodo %s inicializado con direcciones %v", n.Name, addresses)
            53  	return n, nil
            54  }
            55  
            56  // SendMessageSync envía un mensaje de forma síncrona y espera una respuesta.
            57  func (n *AbstractNode) SendMessageSync(address string, message string) (string, error) {
            58  	// Creación del socket REQ (Request) para enviar el mensaje
            59  	var socket *zmq.Socket
            60  	socket, err := n.Context.NewSocket(zmq.REQ)
            61  	if err != nil {
            62  		n.Logger.Printf("Error al crear el socket REQ: %v", err) // Traza adicional
            63  		return "", errors.New("error al crear el socket REQ")
            64  	}
            65  	defer socket.Close()
            66  
            67  	// Establecer el timeout para recibir respuestas
            68  	socket.SetRcvtimeo(n.Timeout * time.Millisecond) // Convertir el timeout a milisegundos
            69  
            70  	// Traza: Mostrar el valor del timeout configurado
            71  	n.Logger.Printf("Timeout de recepción configurado a: %v milisegundos", int64(n.Timeout)) // Traza para el timeout
            72  
            73  	// Conectar al socket en la dirección proporcionada
            74  	err = socket.Connect("tcp://" + address)
            75  	if err != nil {
            76  		n.Logger.Printf("Error al conectar con %s: %v", address, err) // Traza adicional
            77  		return "", errors.New("error al conectar con " + address)
            78  	}
            79  
            80  	n.Logger.Printf("Conectado a %s", address) // Traza para verificar la conexión
            81  
            82  	// Enviar el mensaje al servidor
            83  	_, err = socket.Send(message, 0)
            84  	if err != nil {
            85  		n.Logger.Printf("Error al enviar el mensaje a %s: %v", address, err) // Traza adicional
            86  		return "", errors.New("error al enviar el mensaje")
            87  	}
            88  
            89  	n.Logger.Printf("Mensaje enviado a %s: %s", address, message) // Traza de envío
            90  
            91  	// Intentar recibir la respuesta
            92  	reply, err := socket.Recv(0)
            93  	if err != nil {
            94  		n.Logger.Printf("Error al recibir respuesta de %s: %v", address, err) // Traza para el error de recepción
            95  		return "", errors.New("no se recibió respuesta del socket")
            96  	}
            97  
            98  	n.Logger.Printf("Respuesta recibida de %s: %s", address, reply) // Traza de respuesta recibida
            99  	return reply, nil
           100  }
           101  
           102  // SendMessageAsync envía un mensaje de manera asíncrona.
           103  func (n *AbstractNode) SendMessageAsync(address, message string) error {
           104  	socket, err := n.Context.NewSocket(zmq.PUSH)
           105  	if err != nil {
           106  		return errors.New("error al crear el socket PUSH")
           107  	}
           108  	defer socket.Close()
           109  
           110  	err = socket.Connect("tcp://" + address)
           111  	if err != nil {
           112  		return errors.New("error al conectar con " + address)
           113  	}
           114  
           115  	_, err = socket.Send(message, 0)
           116  	if err != nil {
           117  		return errors.New("error al enviar el mensaje")
           118  	}
           119  
           120  	n.Logger.Printf("Mensaje asincrónico enviado a %s: %s", address, message)
           121  	return nil
           122  }
           123  
           124  // StartListening inicia el proceso de escucha para mensajes entrantes en el nodo.
           125  // Configura un socket de tipo REP (Response) para recibir y responder a mensajes.
           126  func (n *AbstractNode) StartListening() error {
           127  	// Log para indicar que estamos intentando crear un socket REP.
           128  	n.Logger.Printf("Intentando crear un socket REP para el nodo %s en la dirección %s", n.Name, n.Address)
           129  	socket, err := n.Context.NewSocket(zmq.REP)
           130  	if err != nil {
           131  		// Si ocurre un error al crear el socket, loguea el error y retorna un mensaje de error.
           132  		n.Logger.Printf("Error al crear el socket REP: %v", err)
           133  		return errors.New("error al crear el socket REP")
           134  	}
           135  	n.Socket = socket
           136  	n.Logger.Printf("Socket REP creado exitosamente para el nodo %s", n.Name)
           137  
           138  	// Enlaza el socket a la dirección TCP proporcionada en el nodo para esperar conexiones.
           139  	n.Logger.Printf("Enlazando el socket REP en la dirección tcp://%s", n.Address)
           140  	err = socket.Bind("tcp://" + n.Address)
           141  	if err != nil {
           142  		// Si ocurre un error al enlazar el socket, loguea el error y retorna un mensaje de error.
           143  		n.Logger.Printf("Error al enlazar el socket en %s: %v", n.Address, err)
           144  		return errors.New("error al enlazar el socket en " + n.Address)
           145  	}
           146  	n.Logger.Printf("Socket enlazado exitosamente en %s", n.Address)
           147  
           148  	// Inicia una nueva goroutine para escuchar de manera concurrente sin bloquear el hilo principal.
           149  	n.Logger.Printf("Iniciando goroutine para escuchar en el nodo %s", n.Name)
           150  	go func() {
           151  		// Logea que el nodo ha comenzado a escuchar en la dirección configurada.
           152  		n.Logger.Printf("Nodo %s escuchando en %s", n.Name, n.Address)
           153  
           154  		// Entra en un bucle infinito para recibir y procesar mensajes.
           155  		for {
           156  			// Recibe un mensaje del socket.
           157  			n.Logger.Printf("Esperando mensaje en %s...", n.Name)
           158  			message, err := socket.Recv(0)
           159  			if err != nil {
           160  				// Si ocurre un error al recibir el mensaje, loguea el error y termina el bucle.
           161  				n.Logger.Printf("Error al recibir mensaje: %v", err)
           162  				break
           163  			}
           164  			n.Logger.Printf("Mensaje recibido en %s: %v", n.Name, message)
           165  
           166  			// Llama al método HandleProcess, que es implementado por el tipo real de nodo (Follower, Leader, etc.).
           167  			// Este método procesará el mensaje recibido y generará una respuesta.
           168  			n.Logger.Printf("Procesando mensaje en %s...", n.Name)
           169  			response, err := n.Handler.HandleProcess(message)
           170  			if err != nil {
           171  				// Si hay un error al procesar el mensaje, loguea el error y termina el bucle.
           172  				n.Logger.Printf("Error en HandleProcess en %s: %v", n.Name, err)
           173  				break
           174  			}
           175  
           176  			// Envía la respuesta de vuelta al cliente a través del socket.
           177  			n.Logger.Printf("Enviando respuesta en %s: %v", n.Name, response)
           178  			_, err = socket.Send(response, 0)
           179  			if err != nil {
           180  				// Si ocurre un error al enviar la respuesta, loguea el error y termina el bucle.
           181  				n.Logger.Printf("Error al enviar respuesta en %s: %v", n.Name, err)
           182  				break
           183  			}
           184  		}
           185  	}()
           186  
           187  	// La función regresa nil si todo se configura correctamente y la goroutine se inicia sin errores.
           188  	n.Logger.Printf("Escucha iniciada exitosamente en el nodo %s", n.Name)
           189  	return nil
           190  }
           191  
           192  // Close cierra los recursos del nodo.
           193  func (n *AbstractNode) Close() error {
           194  	if n.Socket != nil {
           195  		n.Socket.Close()
           196  		n.Logger.Printf("Socket cerrado para el nodo %s", n.Name)
           197  	}
           198  	if n.Context != nil {
           199  		n.Context.Term()
           200  		n.Logger.Printf("Contexto cerrado para el nodo %s", n.Name)
           201  	}
           202  	return nil
           203  }
           204  
           205  // handleProcess debe ser sobrescrito por las subclases para procesar mensajes.
           206  func (n *AbstractNode) handleProcess(message string) string {
           207  	n.Logger.Printf("Procesando mensaje: %s", message)
           208  	return `{"status":"unhandled"}`
           209  }
           210  
        

        View as plain text

        src/goberkeley/berkeley/anode.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/anode.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"errors"
             5  	"log"
             6  	"time"
             7  
             8  	zmq "github.com/pebbe/zmq4" // Librería para trabajar con ZeroMQ
             9  )
            10  
            11  // Interfaz Handler con el método HandleProcess
            12  type Handler interface {
            13  	HandleProcess(message string) (string, error)
            14  }
            15  
            16  // AbstractNode proporciona la funcionalidad base para nodos en el sistema.
            17  type AbstractNode struct {
            18  	Name          string
            19  	Address       string
            20  	Timeout       time.Duration
            21  	NodeAddresses map[string]string
            22  	Context       *zmq.Context
            23  	Socket        *zmq.Socket
            24  	Logger        *log.Logger
            25  	Handler       // Composición de la interfaz Handler
            26  }
            27  
            28  // NewAbstractNode crea e inicializa un nuevo nodo base.
            29  func NewAbstractNode(name, address string, timeout time.Duration) (*AbstractNode, error) {
            30  	context, err := zmq.NewContext()
            31  	if err != nil {
            32  		return nil, errors.New("error al crear el contexto ZeroMQ")
            33  	}
            34  
            35  	return &AbstractNode{
            36  		Name:    name,
            37  		Address: address,
            38  		Timeout: timeout,
            39  		Context: context,
            40  		Logger:  log.Default(),
            41  	}, nil
            42  }
            43  
            44  // InitializeNodeWithAddresses inicializa un nodo con direcciones de otros nodos.
            45  func InitializeNodeWithAddresses(name, address string, timeout time.Duration, addresses map[string]string) (*AbstractNode, error) {
            46  	var n *AbstractNode
            47  	n, err := NewAbstractNode(name, address, timeout)
            48  	if err != nil {
            49  		return nil, err
            50  	}
            51  	n.NodeAddresses = addresses
            52  	n.Logger.Printf("Nodo %s inicializado con direcciones %v", n.Name, addresses)
            53  	return n, nil
            54  }
            55  
            56  // SendMessageSync envía un mensaje de forma síncrona y espera una respuesta.
            57  func (n *AbstractNode) SendMessageSync(address string, message string) (string, error) {
            58  	// Creación del socket REQ (Request) para enviar el mensaje
            59  	var socket *zmq.Socket
            60  	socket, err := n.Context.NewSocket(zmq.REQ)
            61  	if err != nil {
            62  		n.Logger.Printf("Error al crear el socket REQ: %v", err) // Traza adicional
            63  		return "", errors.New("error al crear el socket REQ")
            64  	}
            65  	defer socket.Close()
            66  
            67  	// Establecer el timeout para recibir respuestas
            68  	socket.SetRcvtimeo(n.Timeout * time.Millisecond) // Convertir el timeout a milisegundos
            69  
            70  	// Traza: Mostrar el valor del timeout configurado
            71  	n.Logger.Printf("Timeout de recepción configurado a: %v milisegundos", int64(n.Timeout)) // Traza para el timeout
            72  
            73  	// Conectar al socket en la dirección proporcionada
            74  	err = socket.Connect("tcp://" + address)
            75  	if err != nil {
            76  		n.Logger.Printf("Error al conectar con %s: %v", address, err) // Traza adicional
            77  		return "", errors.New("error al conectar con " + address)
            78  	}
            79  
            80  	n.Logger.Printf("Conectado a %s", address) // Traza para verificar la conexión
            81  
            82  	// Enviar el mensaje al servidor
            83  	_, err = socket.Send(message, 0)
            84  	if err != nil {
            85  		n.Logger.Printf("Error al enviar el mensaje a %s: %v", address, err) // Traza adicional
            86  		return "", errors.New("error al enviar el mensaje")
            87  	}
            88  
            89  	n.Logger.Printf("Mensaje enviado a %s: %s", address, message) // Traza de envío
            90  
            91  	// Intentar recibir la respuesta
            92  	reply, err := socket.Recv(0)
            93  	if err != nil {
            94  		n.Logger.Printf("Error al recibir respuesta de %s: %v", address, err) // Traza para el error de recepción
            95  		return "", errors.New("no se recibió respuesta del socket")
            96  	}
            97  
            98  	n.Logger.Printf("Respuesta recibida de %s: %s", address, reply) // Traza de respuesta recibida
            99  	return reply, nil
           100  }
           101  
           102  // SendMessageAsync envía un mensaje de manera asíncrona.
           103  func (n *AbstractNode) SendMessageAsync(address, message string) error {
           104  	socket, err := n.Context.NewSocket(zmq.PUSH)
           105  	if err != nil {
           106  		return errors.New("error al crear el socket PUSH")
           107  	}
           108  	defer socket.Close()
           109  
           110  	err = socket.Connect("tcp://" + address)
           111  	if err != nil {
           112  		return errors.New("error al conectar con " + address)
           113  	}
           114  
           115  	_, err = socket.Send(message, 0)
           116  	if err != nil {
           117  		return errors.New("error al enviar el mensaje")
           118  	}
           119  
           120  	n.Logger.Printf("Mensaje asincrónico enviado a %s: %s", address, message)
           121  	return nil
           122  }
           123  
           124  // StartListening inicia el proceso de escucha para mensajes entrantes en el nodo.
           125  // Configura un socket de tipo REP (Response) para recibir y responder a mensajes.
           126  func (n *AbstractNode) StartListening() error {
           127  	// Log para indicar que estamos intentando crear un socket REP.
           128  	n.Logger.Printf("Intentando crear un socket REP para el nodo %s en la dirección %s", n.Name, n.Address)
           129  	socket, err := n.Context.NewSocket(zmq.REP)
           130  	if err != nil {
           131  		// Si ocurre un error al crear el socket, loguea el error y retorna un mensaje de error.
           132  		n.Logger.Printf("Error al crear el socket REP: %v", err)
           133  		return errors.New("error al crear el socket REP")
           134  	}
           135  	n.Socket = socket
           136  	n.Logger.Printf("Socket REP creado exitosamente para el nodo %s", n.Name)
           137  
           138  	// Enlaza el socket a la dirección TCP proporcionada en el nodo para esperar conexiones.
           139  	n.Logger.Printf("Enlazando el socket REP en la dirección tcp://%s", n.Address)
           140  	err = socket.Bind("tcp://" + n.Address)
           141  	if err != nil {
           142  		// Si ocurre un error al enlazar el socket, loguea el error y retorna un mensaje de error.
           143  		n.Logger.Printf("Error al enlazar el socket en %s: %v", n.Address, err)
           144  		return errors.New("error al enlazar el socket en " + n.Address)
           145  	}
           146  	n.Logger.Printf("Socket enlazado exitosamente en %s", n.Address)
           147  
           148  	// Inicia una nueva goroutine para escuchar de manera concurrente sin bloquear el hilo principal.
           149  	n.Logger.Printf("Iniciando goroutine para escuchar en el nodo %s", n.Name)
           150  	go func() {
           151  		// Logea que el nodo ha comenzado a escuchar en la dirección configurada.
           152  		n.Logger.Printf("Nodo %s escuchando en %s", n.Name, n.Address)
           153  
           154  		// Entra en un bucle infinito para recibir y procesar mensajes.
           155  		for {
           156  			// Recibe un mensaje del socket.
           157  			n.Logger.Printf("Esperando mensaje en %s...", n.Name)
           158  			message, err := socket.Recv(0)
           159  			if err != nil {
           160  				// Si ocurre un error al recibir el mensaje, loguea el error y termina el bucle.
           161  				n.Logger.Printf("Error al recibir mensaje: %v", err)
           162  				break
           163  			}
           164  			n.Logger.Printf("Mensaje recibido en %s: %v", n.Name, message)
           165  
           166  			// Llama al método HandleProcess, que es implementado por el tipo real de nodo (Follower, Leader, etc.).
           167  			// Este método procesará el mensaje recibido y generará una respuesta.
           168  			n.Logger.Printf("Procesando mensaje en %s...", n.Name)
           169  			response, err := n.Handler.HandleProcess(message)
           170  			if err != nil {
           171  				// Si hay un error al procesar el mensaje, loguea el error y termina el bucle.
           172  				n.Logger.Printf("Error en HandleProcess en %s: %v", n.Name, err)
           173  				break
           174  			}
           175  
           176  			// Envía la respuesta de vuelta al cliente a través del socket.
           177  			n.Logger.Printf("Enviando respuesta en %s: %v", n.Name, response)
           178  			_, err = socket.Send(response, 0)
           179  			if err != nil {
           180  				// Si ocurre un error al enviar la respuesta, loguea el error y termina el bucle.
           181  				n.Logger.Printf("Error al enviar respuesta en %s: %v", n.Name, err)
           182  				break
           183  			}
           184  		}
           185  	}()
           186  
           187  	// La función regresa nil si todo se configura correctamente y la goroutine se inicia sin errores.
           188  	n.Logger.Printf("Escucha iniciada exitosamente en el nodo %s", n.Name)
           189  	return nil
           190  }
           191  
           192  // Close cierra los recursos del nodo.
           193  func (n *AbstractNode) Close() error {
           194  	if n.Socket != nil {
           195  		n.Socket.Close()
           196  		n.Logger.Printf("Socket cerrado para el nodo %s", n.Name)
           197  	}
           198  	if n.Context != nil {
           199  		n.Context.Term()
           200  		n.Logger.Printf("Contexto cerrado para el nodo %s", n.Name)
           201  	}
           202  	return nil
           203  }
           204  
           205  // handleProcess debe ser sobrescrito por las subclases para procesar mensajes.
           206  func (n *AbstractNode) handleProcess(message string) string {
           207  	n.Logger.Printf("Procesando mensaje: %s", message)
           208  	return `{"status":"unhandled"}`
           209  }
           210  
        

        View as plain text

        src/goberkeley/berkeley/anode.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/anode.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"errors"
             5  	"log"
             6  	"time"
             7  
             8  	zmq "github.com/pebbe/zmq4" // Librería para trabajar con ZeroMQ
             9  )
            10  
            11  // Interfaz Handler con el método HandleProcess
            12  type Handler interface {
            13  	HandleProcess(message string) (string, error)
            14  }
            15  
            16  // AbstractNode proporciona la funcionalidad base para nodos en el sistema.
            17  type AbstractNode struct {
            18  	Name          string
            19  	Address       string
            20  	Timeout       time.Duration
            21  	NodeAddresses map[string]string
            22  	Context       *zmq.Context
            23  	Socket        *zmq.Socket
            24  	Logger        *log.Logger
            25  	Handler       // Composición de la interfaz Handler
            26  }
            27  
            28  // NewAbstractNode crea e inicializa un nuevo nodo base.
            29  func NewAbstractNode(name, address string, timeout time.Duration) (*AbstractNode, error) {
            30  	context, err := zmq.NewContext()
            31  	if err != nil {
            32  		return nil, errors.New("error al crear el contexto ZeroMQ")
            33  	}
            34  
            35  	return &AbstractNode{
            36  		Name:    name,
            37  		Address: address,
            38  		Timeout: timeout,
            39  		Context: context,
            40  		Logger:  log.Default(),
            41  	}, nil
            42  }
            43  
            44  // InitializeNodeWithAddresses inicializa un nodo con direcciones de otros nodos.
            45  func InitializeNodeWithAddresses(name, address string, timeout time.Duration, addresses map[string]string) (*AbstractNode, error) {
            46  	var n *AbstractNode
            47  	n, err := NewAbstractNode(name, address, timeout)
            48  	if err != nil {
            49  		return nil, err
            50  	}
            51  	n.NodeAddresses = addresses
            52  	n.Logger.Printf("Nodo %s inicializado con direcciones %v", n.Name, addresses)
            53  	return n, nil
            54  }
            55  
            56  // SendMessageSync envía un mensaje de forma síncrona y espera una respuesta.
            57  func (n *AbstractNode) SendMessageSync(address string, message string) (string, error) {
            58  	// Creación del socket REQ (Request) para enviar el mensaje
            59  	var socket *zmq.Socket
            60  	socket, err := n.Context.NewSocket(zmq.REQ)
            61  	if err != nil {
            62  		n.Logger.Printf("Error al crear el socket REQ: %v", err) // Traza adicional
            63  		return "", errors.New("error al crear el socket REQ")
            64  	}
            65  	defer socket.Close()
            66  
            67  	// Establecer el timeout para recibir respuestas
            68  	socket.SetRcvtimeo(n.Timeout * time.Millisecond) // Convertir el timeout a milisegundos
            69  
            70  	// Traza: Mostrar el valor del timeout configurado
            71  	n.Logger.Printf("Timeout de recepción configurado a: %v milisegundos", int64(n.Timeout)) // Traza para el timeout
            72  
            73  	// Conectar al socket en la dirección proporcionada
            74  	err = socket.Connect("tcp://" + address)
            75  	if err != nil {
            76  		n.Logger.Printf("Error al conectar con %s: %v", address, err) // Traza adicional
            77  		return "", errors.New("error al conectar con " + address)
            78  	}
            79  
            80  	n.Logger.Printf("Conectado a %s", address) // Traza para verificar la conexión
            81  
            82  	// Enviar el mensaje al servidor
            83  	_, err = socket.Send(message, 0)
            84  	if err != nil {
            85  		n.Logger.Printf("Error al enviar el mensaje a %s: %v", address, err) // Traza adicional
            86  		return "", errors.New("error al enviar el mensaje")
            87  	}
            88  
            89  	n.Logger.Printf("Mensaje enviado a %s: %s", address, message) // Traza de envío
            90  
            91  	// Intentar recibir la respuesta
            92  	reply, err := socket.Recv(0)
            93  	if err != nil {
            94  		n.Logger.Printf("Error al recibir respuesta de %s: %v", address, err) // Traza para el error de recepción
            95  		return "", errors.New("no se recibió respuesta del socket")
            96  	}
            97  
            98  	n.Logger.Printf("Respuesta recibida de %s: %s", address, reply) // Traza de respuesta recibida
            99  	return reply, nil
           100  }
           101  
           102  // SendMessageAsync envía un mensaje de manera asíncrona.
           103  func (n *AbstractNode) SendMessageAsync(address, message string) error {
           104  	socket, err := n.Context.NewSocket(zmq.PUSH)
           105  	if err != nil {
           106  		return errors.New("error al crear el socket PUSH")
           107  	}
           108  	defer socket.Close()
           109  
           110  	err = socket.Connect("tcp://" + address)
           111  	if err != nil {
           112  		return errors.New("error al conectar con " + address)
           113  	}
           114  
           115  	_, err = socket.Send(message, 0)
           116  	if err != nil {
           117  		return errors.New("error al enviar el mensaje")
           118  	}
           119  
           120  	n.Logger.Printf("Mensaje asincrónico enviado a %s: %s", address, message)
           121  	return nil
           122  }
           123  
           124  // StartListening inicia el proceso de escucha para mensajes entrantes en el nodo.
           125  // Configura un socket de tipo REP (Response) para recibir y responder a mensajes.
           126  func (n *AbstractNode) StartListening() error {
           127  	// Log para indicar que estamos intentando crear un socket REP.
           128  	n.Logger.Printf("Intentando crear un socket REP para el nodo %s en la dirección %s", n.Name, n.Address)
           129  	socket, err := n.Context.NewSocket(zmq.REP)
           130  	if err != nil {
           131  		// Si ocurre un error al crear el socket, loguea el error y retorna un mensaje de error.
           132  		n.Logger.Printf("Error al crear el socket REP: %v", err)
           133  		return errors.New("error al crear el socket REP")
           134  	}
           135  	n.Socket = socket
           136  	n.Logger.Printf("Socket REP creado exitosamente para el nodo %s", n.Name)
           137  
           138  	// Enlaza el socket a la dirección TCP proporcionada en el nodo para esperar conexiones.
           139  	n.Logger.Printf("Enlazando el socket REP en la dirección tcp://%s", n.Address)
           140  	err = socket.Bind("tcp://" + n.Address)
           141  	if err != nil {
           142  		// Si ocurre un error al enlazar el socket, loguea el error y retorna un mensaje de error.
           143  		n.Logger.Printf("Error al enlazar el socket en %s: %v", n.Address, err)
           144  		return errors.New("error al enlazar el socket en " + n.Address)
           145  	}
           146  	n.Logger.Printf("Socket enlazado exitosamente en %s", n.Address)
           147  
           148  	// Inicia una nueva goroutine para escuchar de manera concurrente sin bloquear el hilo principal.
           149  	n.Logger.Printf("Iniciando goroutine para escuchar en el nodo %s", n.Name)
           150  	go func() {
           151  		// Logea que el nodo ha comenzado a escuchar en la dirección configurada.
           152  		n.Logger.Printf("Nodo %s escuchando en %s", n.Name, n.Address)
           153  
           154  		// Entra en un bucle infinito para recibir y procesar mensajes.
           155  		for {
           156  			// Recibe un mensaje del socket.
           157  			n.Logger.Printf("Esperando mensaje en %s...", n.Name)
           158  			message, err := socket.Recv(0)
           159  			if err != nil {
           160  				// Si ocurre un error al recibir el mensaje, loguea el error y termina el bucle.
           161  				n.Logger.Printf("Error al recibir mensaje: %v", err)
           162  				break
           163  			}
           164  			n.Logger.Printf("Mensaje recibido en %s: %v", n.Name, message)
           165  
           166  			// Llama al método HandleProcess, que es implementado por el tipo real de nodo (Follower, Leader, etc.).
           167  			// Este método procesará el mensaje recibido y generará una respuesta.
           168  			n.Logger.Printf("Procesando mensaje en %s...", n.Name)
           169  			response, err := n.Handler.HandleProcess(message)
           170  			if err != nil {
           171  				// Si hay un error al procesar el mensaje, loguea el error y termina el bucle.
           172  				n.Logger.Printf("Error en HandleProcess en %s: %v", n.Name, err)
           173  				break
           174  			}
           175  
           176  			// Envía la respuesta de vuelta al cliente a través del socket.
           177  			n.Logger.Printf("Enviando respuesta en %s: %v", n.Name, response)
           178  			_, err = socket.Send(response, 0)
           179  			if err != nil {
           180  				// Si ocurre un error al enviar la respuesta, loguea el error y termina el bucle.
           181  				n.Logger.Printf("Error al enviar respuesta en %s: %v", n.Name, err)
           182  				break
           183  			}
           184  		}
           185  	}()
           186  
           187  	// La función regresa nil si todo se configura correctamente y la goroutine se inicia sin errores.
           188  	n.Logger.Printf("Escucha iniciada exitosamente en el nodo %s", n.Name)
           189  	return nil
           190  }
           191  
           192  // Close cierra los recursos del nodo.
           193  func (n *AbstractNode) Close() error {
           194  	if n.Socket != nil {
           195  		n.Socket.Close()
           196  		n.Logger.Printf("Socket cerrado para el nodo %s", n.Name)
           197  	}
           198  	if n.Context != nil {
           199  		n.Context.Term()
           200  		n.Logger.Printf("Contexto cerrado para el nodo %s", n.Name)
           201  	}
           202  	return nil
           203  }
           204  
           205  // handleProcess debe ser sobrescrito por las subclases para procesar mensajes.
           206  func (n *AbstractNode) handleProcess(message string) string {
           207  	n.Logger.Printf("Procesando mensaje: %s", message)
           208  	return `{"status":"unhandled"}`
           209  }
           210  
        

        View as plain text

        src/goberkeley/berkeley/anode.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/anode.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"errors"
             5  	"log"
             6  	"time"
             7  
             8  	zmq "github.com/pebbe/zmq4" // Librería para trabajar con ZeroMQ
             9  )
            10  
            11  // Interfaz Handler con el método HandleProcess
            12  type Handler interface {
            13  	HandleProcess(message string) (string, error)
            14  }
            15  
            16  // AbstractNode proporciona la funcionalidad base para nodos en el sistema.
            17  type AbstractNode struct {
            18  	Name          string
            19  	Address       string
            20  	Timeout       time.Duration
            21  	NodeAddresses map[string]string
            22  	Context       *zmq.Context
            23  	Socket        *zmq.Socket
            24  	Logger        *log.Logger
            25  	Handler       // Composición de la interfaz Handler
            26  }
            27  
            28  // NewAbstractNode crea e inicializa un nuevo nodo base.
            29  func NewAbstractNode(name, address string, timeout time.Duration) (*AbstractNode, error) {
            30  	context, err := zmq.NewContext()
            31  	if err != nil {
            32  		return nil, errors.New("error al crear el contexto ZeroMQ")
            33  	}
            34  
            35  	return &AbstractNode{
            36  		Name:    name,
            37  		Address: address,
            38  		Timeout: timeout,
            39  		Context: context,
            40  		Logger:  log.Default(),
            41  	}, nil
            42  }
            43  
            44  // InitializeNodeWithAddresses inicializa un nodo con direcciones de otros nodos.
            45  func InitializeNodeWithAddresses(name, address string, timeout time.Duration, addresses map[string]string) (*AbstractNode, error) {
            46  	var n *AbstractNode
            47  	n, err := NewAbstractNode(name, address, timeout)
            48  	if err != nil {
            49  		return nil, err
            50  	}
            51  	n.NodeAddresses = addresses
            52  	n.Logger.Printf("Nodo %s inicializado con direcciones %v", n.Name, addresses)
            53  	return n, nil
            54  }
            55  
            56  // SendMessageSync envía un mensaje de forma síncrona y espera una respuesta.
            57  func (n *AbstractNode) SendMessageSync(address string, message string) (string, error) {
            58  	// Creación del socket REQ (Request) para enviar el mensaje
            59  	var socket *zmq.Socket
            60  	socket, err := n.Context.NewSocket(zmq.REQ)
            61  	if err != nil {
            62  		n.Logger.Printf("Error al crear el socket REQ: %v", err) // Traza adicional
            63  		return "", errors.New("error al crear el socket REQ")
            64  	}
            65  	defer socket.Close()
            66  
            67  	// Establecer el timeout para recibir respuestas
            68  	socket.SetRcvtimeo(n.Timeout * time.Millisecond) // Convertir el timeout a milisegundos
            69  
            70  	// Traza: Mostrar el valor del timeout configurado
            71  	n.Logger.Printf("Timeout de recepción configurado a: %v milisegundos", int64(n.Timeout)) // Traza para el timeout
            72  
            73  	// Conectar al socket en la dirección proporcionada
            74  	err = socket.Connect("tcp://" + address)
            75  	if err != nil {
            76  		n.Logger.Printf("Error al conectar con %s: %v", address, err) // Traza adicional
            77  		return "", errors.New("error al conectar con " + address)
            78  	}
            79  
            80  	n.Logger.Printf("Conectado a %s", address) // Traza para verificar la conexión
            81  
            82  	// Enviar el mensaje al servidor
            83  	_, err = socket.Send(message, 0)
            84  	if err != nil {
            85  		n.Logger.Printf("Error al enviar el mensaje a %s: %v", address, err) // Traza adicional
            86  		return "", errors.New("error al enviar el mensaje")
            87  	}
            88  
            89  	n.Logger.Printf("Mensaje enviado a %s: %s", address, message) // Traza de envío
            90  
            91  	// Intentar recibir la respuesta
            92  	reply, err := socket.Recv(0)
            93  	if err != nil {
            94  		n.Logger.Printf("Error al recibir respuesta de %s: %v", address, err) // Traza para el error de recepción
            95  		return "", errors.New("no se recibió respuesta del socket")
            96  	}
            97  
            98  	n.Logger.Printf("Respuesta recibida de %s: %s", address, reply) // Traza de respuesta recibida
            99  	return reply, nil
           100  }
           101  
           102  // SendMessageAsync envía un mensaje de manera asíncrona.
           103  func (n *AbstractNode) SendMessageAsync(address, message string) error {
           104  	socket, err := n.Context.NewSocket(zmq.PUSH)
           105  	if err != nil {
           106  		return errors.New("error al crear el socket PUSH")
           107  	}
           108  	defer socket.Close()
           109  
           110  	err = socket.Connect("tcp://" + address)
           111  	if err != nil {
           112  		return errors.New("error al conectar con " + address)
           113  	}
           114  
           115  	_, err = socket.Send(message, 0)
           116  	if err != nil {
           117  		return errors.New("error al enviar el mensaje")
           118  	}
           119  
           120  	n.Logger.Printf("Mensaje asincrónico enviado a %s: %s", address, message)
           121  	return nil
           122  }
           123  
           124  // StartListening inicia el proceso de escucha para mensajes entrantes en el nodo.
           125  // Configura un socket de tipo REP (Response) para recibir y responder a mensajes.
           126  func (n *AbstractNode) StartListening() error {
           127  	// Log para indicar que estamos intentando crear un socket REP.
           128  	n.Logger.Printf("Intentando crear un socket REP para el nodo %s en la dirección %s", n.Name, n.Address)
           129  	socket, err := n.Context.NewSocket(zmq.REP)
           130  	if err != nil {
           131  		// Si ocurre un error al crear el socket, loguea el error y retorna un mensaje de error.
           132  		n.Logger.Printf("Error al crear el socket REP: %v", err)
           133  		return errors.New("error al crear el socket REP")
           134  	}
           135  	n.Socket = socket
           136  	n.Logger.Printf("Socket REP creado exitosamente para el nodo %s", n.Name)
           137  
           138  	// Enlaza el socket a la dirección TCP proporcionada en el nodo para esperar conexiones.
           139  	n.Logger.Printf("Enlazando el socket REP en la dirección tcp://%s", n.Address)
           140  	err = socket.Bind("tcp://" + n.Address)
           141  	if err != nil {
           142  		// Si ocurre un error al enlazar el socket, loguea el error y retorna un mensaje de error.
           143  		n.Logger.Printf("Error al enlazar el socket en %s: %v", n.Address, err)
           144  		return errors.New("error al enlazar el socket en " + n.Address)
           145  	}
           146  	n.Logger.Printf("Socket enlazado exitosamente en %s", n.Address)
           147  
           148  	// Inicia una nueva goroutine para escuchar de manera concurrente sin bloquear el hilo principal.
           149  	n.Logger.Printf("Iniciando goroutine para escuchar en el nodo %s", n.Name)
           150  	go func() {
           151  		// Logea que el nodo ha comenzado a escuchar en la dirección configurada.
           152  		n.Logger.Printf("Nodo %s escuchando en %s", n.Name, n.Address)
           153  
           154  		// Entra en un bucle infinito para recibir y procesar mensajes.
           155  		for {
           156  			// Recibe un mensaje del socket.
           157  			n.Logger.Printf("Esperando mensaje en %s...", n.Name)
           158  			message, err := socket.Recv(0)
           159  			if err != nil {
           160  				// Si ocurre un error al recibir el mensaje, loguea el error y termina el bucle.
           161  				n.Logger.Printf("Error al recibir mensaje: %v", err)
           162  				break
           163  			}
           164  			n.Logger.Printf("Mensaje recibido en %s: %v", n.Name, message)
           165  
           166  			// Llama al método HandleProcess, que es implementado por el tipo real de nodo (Follower, Leader, etc.).
           167  			// Este método procesará el mensaje recibido y generará una respuesta.
           168  			n.Logger.Printf("Procesando mensaje en %s...", n.Name)
           169  			response, err := n.Handler.HandleProcess(message)
           170  			if err != nil {
           171  				// Si hay un error al procesar el mensaje, loguea el error y termina el bucle.
           172  				n.Logger.Printf("Error en HandleProcess en %s: %v", n.Name, err)
           173  				break
           174  			}
           175  
           176  			// Envía la respuesta de vuelta al cliente a través del socket.
           177  			n.Logger.Printf("Enviando respuesta en %s: %v", n.Name, response)
           178  			_, err = socket.Send(response, 0)
           179  			if err != nil {
           180  				// Si ocurre un error al enviar la respuesta, loguea el error y termina el bucle.
           181  				n.Logger.Printf("Error al enviar respuesta en %s: %v", n.Name, err)
           182  				break
           183  			}
           184  		}
           185  	}()
           186  
           187  	// La función regresa nil si todo se configura correctamente y la goroutine se inicia sin errores.
           188  	n.Logger.Printf("Escucha iniciada exitosamente en el nodo %s", n.Name)
           189  	return nil
           190  }
           191  
           192  // Close cierra los recursos del nodo.
           193  func (n *AbstractNode) Close() error {
           194  	if n.Socket != nil {
           195  		n.Socket.Close()
           196  		n.Logger.Printf("Socket cerrado para el nodo %s", n.Name)
           197  	}
           198  	if n.Context != nil {
           199  		n.Context.Term()
           200  		n.Logger.Printf("Contexto cerrado para el nodo %s", n.Name)
           201  	}
           202  	return nil
           203  }
           204  
           205  // handleProcess debe ser sobrescrito por las subclases para procesar mensajes.
           206  func (n *AbstractNode) handleProcess(message string) string {
           207  	n.Logger.Printf("Procesando mensaje: %s", message)
           208  	return `{"status":"unhandled"}`
           209  }
           210  
        

        View as plain text

        src/goberkeley/berkeley/config.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/config.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  	"os"
             7  	"time"
             8  )
             9  
            10  type LeaderConfig struct {
            11  	Name    string `json:"name"`
            12  	Address string `json:"address"`
            13  }
            14  
            15  type FollowerConfig struct {
            16  	Name    string `json:"name"`
            17  	Address string `json:"address"`
            18  }
            19  
            20  type Config struct {
            21  	Leader    LeaderConfig     `json:"leader"`
            22  	Followers []FollowerConfig `json:"followers"`
            23  	Timeout   time.Duration    `json:"timeout"`
            24  }
            25  
            26  func LoadConfig(filepath string) *Config {
            27  	// Abrir el archivo JSON
            28  	file, err := os.Open(filepath)
            29  	if err != nil {
            30  		fmt.Println("Error abriendo el archivo:", err)
            31  		return nil
            32  	}
            33  	defer file.Close()
            34  
            35  	// Decodificar el JSON en la estructura Config
            36  	var config Config
            37  	decoder := json.NewDecoder(file)
            38  	if err := decoder.Decode(&config); err != nil {
            39  		fmt.Println("Error decodificando JSON:", err)
            40  		return nil
            41  	}
            42  
            43  	// Imprimir la configuración cargada
            44  	fmt.Printf("Líder: %s (%s)\n", config.Leader.Name, config.Leader.Address)
            45  	for _, follower := range config.Followers {
            46  		fmt.Printf("Seguidor: %s (%s)\n", follower.Name, follower.Address)
            47  	}
            48  	fmt.Printf("Timeout: %d ms\n", config.Timeout)
            49  
            50  	return &config
            51  }
            52  
        

        View as plain text

        src/goberkeley/berkeley/config.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/config.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  	"os"
             7  	"time"
             8  )
             9  
            10  type LeaderConfig struct {
            11  	Name    string `json:"name"`
            12  	Address string `json:"address"`
            13  }
            14  
            15  type FollowerConfig struct {
            16  	Name    string `json:"name"`
            17  	Address string `json:"address"`
            18  }
            19  
            20  type Config struct {
            21  	Leader    LeaderConfig     `json:"leader"`
            22  	Followers []FollowerConfig `json:"followers"`
            23  	Timeout   time.Duration    `json:"timeout"`
            24  }
            25  
            26  func LoadConfig(filepath string) *Config {
            27  	// Abrir el archivo JSON
            28  	file, err := os.Open(filepath)
            29  	if err != nil {
            30  		fmt.Println("Error abriendo el archivo:", err)
            31  		return nil
            32  	}
            33  	defer file.Close()
            34  
            35  	// Decodificar el JSON en la estructura Config
            36  	var config Config
            37  	decoder := json.NewDecoder(file)
            38  	if err := decoder.Decode(&config); err != nil {
            39  		fmt.Println("Error decodificando JSON:", err)
            40  		return nil
            41  	}
            42  
            43  	// Imprimir la configuración cargada
            44  	fmt.Printf("Líder: %s (%s)\n", config.Leader.Name, config.Leader.Address)
            45  	for _, follower := range config.Followers {
            46  		fmt.Printf("Seguidor: %s (%s)\n", follower.Name, follower.Address)
            47  	}
            48  	fmt.Printf("Timeout: %d ms\n", config.Timeout)
            49  
            50  	return &config
            51  }
            52  
        

        View as plain text

        src/goberkeley/berkeley/leader.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/leader.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  
             7  	"log"
             8  	"strconv"
             9  	"sync"
            10  	"time"
            11  )
            12  
            13  // Mensaje JSON que se envía al seguidor.
            14  type TimeRequest struct {
            15  	Message    string `json:"message"`
            16  	Operation  string `json:"operation"`
            17  	Time       int64  `json:"time"`
            18  	LeaderAddr string `json:"leader_address"`
            19  }
            20  type DeltaRequest struct {
            21  	Message    string `json:"message"`
            22  	Operation  string `json:"operation"`
            23  	Delta      int64  `json:"delta"`
            24  	LeaderAddr string `json:"leader_address"`
            25  }
            26  type closeRequest struct {
            27  	Message    string `json:"message"`
            28  	Operation  string `json:"operation"`
            29  	LeaderAddr string `json:"leader_address"`
            30  }
            31  
            32  // Leader representa el nodo líder en el sistema Berkeley.
            33  type Leader struct {
            34  	aAbstractNode          *AbstractNode
            35  	UnreachableFollowers   map[string]*FollowerInfo
            36  	SuccessfulFollowers    map[string]*FollowerInfo
            37  	NonRespondingFollowers map[string]*FollowerInfo
            38  	TimeUpdatedFollowers   map[string]*FollowerInfo
            39  	FailedFollowers        map[string]*FollowerInfo
            40  	//mu                     sync.Mutex // Mutex para proteger los mapas en accesos concurrentes
            41  	Logger *log.Logger
            42  }
            43  
            44  // HandleProcess implements Handler.
            45  func (l *Leader) HandleProcess(message string) (string, error) {
            46  	panic("unimplemented")
            47  }
            48  
            49  // InitializeLeaderNode crea e inicializa un nuevo nodo líder.
            50  func InitializeLeaderNode(name, address string, timeout time.Duration, nodeAddresses map[string]string) (*Leader, error) {
            51  	// Suponiendo que InitializeNodeWithAddresses crea un nodo base y devuelve un puntero a AbstractNode
            52  	baseNode, err := InitializeNodeWithAddresses(name, address, timeout, nodeAddresses)
            53  	if err != nil {
            54  		return nil, err
            55  	}
            56  
            57  	// Inicializamos el líder, asignando el nodo base y un logger
            58  	leader := &Leader{
            59  		aAbstractNode: baseNode, // Asignamos el puntero a AbstractNode
            60  		Logger:        log.Default(),
            61  	}
            62  	leader.aAbstractNode.Handler = leader
            63  
            64  	return leader, nil
            65  }
            66  func (l *Leader) initStructs() {
            67  	if l.UnreachableFollowers == nil {
            68  		l.UnreachableFollowers = make(map[string]*FollowerInfo)
            69  	}
            70  	if l.SuccessfulFollowers == nil {
            71  		l.SuccessfulFollowers = make(map[string]*FollowerInfo)
            72  	}
            73  	if l.NonRespondingFollowers == nil {
            74  		l.NonRespondingFollowers = make(map[string]*FollowerInfo)
            75  	}
            76  	if l.TimeUpdatedFollowers == nil {
            77  		l.TimeUpdatedFollowers = make(map[string]*FollowerInfo)
            78  	}
            79  	if l.FailedFollowers == nil {
            80  		l.FailedFollowers = make(map[string]*FollowerInfo)
            81  	}
            82  }
            83  
            84  // StartAlgorithm implementa el algoritmo de sincronización Berkeley para el líder.
            85  func (l *Leader) StartAlgorithm() {
            86  	l.Logger.Println("Iniciando algoritmo de sincronización Berkeley...")
            87  	l.initStructs()
            88  	// Simula el envío de solicitudes de tiempo a los seguidores
            89  	l.processFollowers()
            90  
            91  	// Fase 2: Calcular el delta con la media de los tiempos
            92  	log.Println("** Fase 2 **: Calcular el delta con la media de los tiempos")
            93  	delta := l.calculateDeltaTimeDifference()
            94  	if delta != 0 {
            95  		// Paso 3: Actualizar relojes de los seguidores
            96  		log.Println("** Paso 3 **: Llamar a los seguidores para actualizar sus relojes")
            97  		l.callFollowersWithUpdatedTime(delta)
            98  
            99  		// Fase 4: Enviar mensaje de cierre
           100  		log.Println("** Fase 4 **: Enviar mensaje de cierre a los seguidores")
           101  		l.sendCloseMessagesToFollowers()
           102  
           103  		// Fase 5: Mostrar los resultados finales
           104  		log.Println("** Fase 5: Mostrar los resultados de la sincronización")
           105  		l.printResults()
           106  	} else {
           107  		// Se registra esta situación para comprobarlo más adelante en los logs
           108  		log.Println("El resultado del delta es cero por lo que no se envían actualizaciones a ningún seguidor.")
           109  	}
           110  }
           111  func (l *Leader) processFollowers() {
           112  	leaderTime := time.Now().UnixMilli() // T0
           113  	leaderAddr := l.aAbstractNode.Address
           114  
           115  	log.Printf("processFollowers: leaderAddr %s leaderTime %d.", leaderAddr, leaderTime)
           116  
           117  	// Lista de seguidores
           118  	followers := l.aAbstractNode.NodeAddresses
           119  
           120  	// Canal para los resultados
           121  	results := make(chan *FollowerInfo, len(followers))
           122  	var wg sync.WaitGroup
           123  
           124  	// Enviar solicitudes a los seguidores concurrentemente
           125  	for followerName, followerAddr := range followers {
           126  		wg.Add(1)
           127  		go func(name, addr string) {
           128  			defer wg.Done()
           129  			log.Printf("Enviando solicitud de tiempo a %s (%s).", name, addr)
           130  			l.sendTimeRequestToFollower(name, addr, leaderTime, leaderAddr, results)
           131  		}(followerName, followerAddr)
           132  	}
           133  
           134  	// Cerrar el canal una vez que todos los goroutines hayan terminado
           135  	go func() {
           136  		wg.Wait()
           137  		close(results)
           138  	}()
           139  
           140  	// Recoger y procesar los resultados
           141  	for res := range results {
           142  		if res.GetState() == "RESPONDED" {
           143  			// Seguidor que respondió correctamente
           144  			l.SuccessfulFollowers[res.GetName()] = res
           145  			log.Printf("Seguidor %s respondió correctamente con tiempo local: %d ms", res.GetName(), res.GetLocalTime())
           146  		} else if res.GetState() == "TIMEOUT" {
           147  			// Seguidor que no respondió a tiempo
           148  			l.NonRespondingFollowers[res.GetName()] = res
           149  			log.Printf("Seguidor %s no respondió a tiempo.", res.GetName())
           150  		} else {
           151  			// Seguidor que tuvo algún otro problema
           152  			l.FailedFollowers[res.GetName()] = res
           153  			log.Printf("Seguidor %s falló con estado: %s.", res.GetName(), res.GetState())
           154  		}
           155  	}
           156  
           157  	// Log final para indicar que el procesamiento de seguidores ha terminado
           158  	log.Printf("Proceso de seguidores completado. Respuestas procesadas: %d, Fallos: %d.", len(l.SuccessfulFollowers), len(l.NonRespondingFollowers))
           159  }
           160  func (l *Leader) sendTimeRequestToFollower(followerName, followerAddr string, leaderTime int64, leaderAddr string, results chan<- *FollowerInfo) {
           161  	// Crear el mensaje JSON
           162  	request := TimeRequest{
           163  		Message:    "Requesting time sync",
           164  		Operation:  "GET_TIME",
           165  		Time:       leaderTime, //T0
           166  		LeaderAddr: leaderAddr,
           167  	}
           168  
           169  	// Serializar el mensaje en formato JSON
           170  	requestData, err := json.Marshal(request)
           171  	if err != nil {
           172  		log.Printf("Error al serializar la solicitud a JSON: %v", err)
           173  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           174  		return
           175  	}
           176  
           177  	// Convertir el JSON a string
           178  	requestString := string(requestData)
           179  	log.Printf("Solicitud enviada a %s: %s", followerAddr, requestString)
           180  
           181  	// Enviar el mensaje al seguidor y recibir la respuesta
           182  	reply, err := l.aAbstractNode.SendMessageSync(followerAddr, requestString)
           183  	if err != nil {
           184  		log.Printf("Error al recibir respuesta de %s: %v", followerAddr, err)
           185  		followError := NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           186  		results <- followError
           187  		return
           188  	}
           189  
           190  	log.Printf("Respuesta recibida de %s: %s", followerAddr, reply)
           191  
           192  	// Deserializar la respuesta JSON
           193  	var response map[string]string
           194  	if err := json.Unmarshal([]byte(reply), &response); err != nil {
           195  		log.Printf("Error al procesar la respuesta de %s: %v", followerAddr, err)
           196  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           197  		return
           198  	}
           199  
           200  	// Calcular la diferencia de tiempo
           201  	endCommTime := time.Now().UnixMilli() // T0
           202  	timeComm := endCommTime - leaderTime
           203  	log.Printf("Tiempo de comunicación: %d ms", timeComm)
           204  
           205  	// Obtener el tiempo local del seguidor
           206  	localTimeStr, ok := response["localTime"]
           207  	if !ok {
           208  		log.Printf("No se encontró el campo 'localTime' en la respuesta de %s", followerAddr)
           209  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           210  		return
           211  	}
           212  
           213  	// Convertir el valor de localTime de string a int64
           214  	localTimeInt64, err := strconv.ParseInt(localTimeStr, 10, 64)
           215  	if err != nil {
           216  		log.Printf("Error al convertir 'localTime' a int64 de %s: %v", followerAddr, err)
           217  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           218  		return
           219  	}
           220  
           221  	// Enviar los resultados al canal
           222  	log.Printf("Tiempo local recibido de %s: %d", followerAddr, localTimeInt64)
           223  	foll := NewFollowerInfo(followerAddr, followerName, localTimeInt64, timeComm, 0)
           224  	foll.SetState(Responded)
           225  	results <- foll
           226  }
           227  
           228  // calculateDeltaTimeDifference calcula la diferencia de tiempo (delta) entre el tiempo local y los tiempos de los seguidores válidos.
           229  func (l *Leader) calculateDeltaTimeDifference() int64 {
           230  	// Log de inicio de la operación de cálculo de la diferencia de tiempo
           231  	log.Println("Calculando la diferencia de tiempo (delta)")
           232  
           233  	// Obtener el tiempo actual del líder
           234  	now := time.Now().UnixMilli()
           235  	var sumTime int64 = 0           // Suma de los tiempos ajustados de los seguidores
           236  	var validFollowersCount int = 0 // Contador de seguidores con respuestas válidas
           237  
           238  	// Recorrer los seguidores exitosos y calcular la diferencia de tiempo para cada uno
           239  	for _, follower := range l.SuccessfulFollowers {
           240  		if follower.DiffTime != int64(^uint64(0)>>1) { // Verificar si el seguidor tiene un tiempo válido (Long.MAX_VALUE en Java)
           241  			followerTime := now + follower.DiffTime // Calcular el tiempo ajustado del seguidor
           242  			sumTime += followerTime                 // Sumar el tiempo ajustado
           243  			validFollowersCount++                   // Incrementar el contador de seguidores válidos
           244  		}
           245  	}
           246  
           247  	// Si se tienen seguidores válidos, calcular la diferencia de tiempo promedio
           248  	if validFollowersCount > 0 {
           249  		newNow := sumTime / int64(validFollowersCount) // Calcular el promedio de los tiempos de los seguidores
           250  		delta := newNow - now                          // Calcular la diferencia de tiempo (delta)
           251  
           252  		// Log de los resultados calculados
           253  		log.Printf("Nuevo tiempo calculado (new_now): %d\n", newNow)
           254  		log.Printf("Diferencia global (δ): %d\n", delta)
           255  
           256  		// Retornar la diferencia de tiempo (delta)
           257  		return delta
           258  	} else {
           259  		// Si no hay seguidores válidos, registrar advertencia y retornar 0
           260  		log.Println("No se han recibido respuestas válidas de los seguidores.")
           261  		return 0
           262  	}
           263  }
           264  
           265  func (l *Leader) callFollowersWithUpdatedTime(delta int64) error {
           266  	log.Printf("Enviando actualización de tiempo a los seguidores con delta: %d", delta)
           267  
           268  	// Crear un canal para gestionar las tareas concurrentes
           269  	ch := make(chan *FollowerInfo, len(l.SuccessfulFollowers))
           270  
           271  	// Usamos un WaitGroup para esperar que todas las goroutines terminen
           272  	var wg sync.WaitGroup
           273  
           274  	// Enviar las tareas en paralelo para cada seguidor
           275  	for _, follower := range l.SuccessfulFollowers {
           276  		wg.Add(1) // Incrementamos el contador del WaitGroup
           277  		go func(follower FollowerInfo) {
           278  			defer wg.Done() // Decrementamos el contador del WaitGroup cuando la goroutine termina
           279  			followerInfo := l.sendTimeUpdateToFollower(follower, delta)
           280  			ch <- followerInfo
           281  		}(*follower)
           282  	}
           283  
           284  	// Iniciar una goroutine para cerrar el canal una vez que todas las goroutines hayan terminado
           285  	go func() {
           286  		wg.Wait() // Esperamos a que todas las goroutines terminen
           287  		close(ch) // Cerramos el canal después de que todas las goroutines hayan enviado sus respuestas
           288  	}()
           289  
           290  	// Procesar las respuestas conforme vayan llegando
           291  	for followerInfo := range ch {
           292  		if followerInfo.State == "TIME_UPDATED" {
           293  			log.Printf("El seguidor %s respondió correctamente al cambio del timer.", followerInfo.Name)
           294  			l.TimeUpdatedFollowers[followerInfo.Name] = followerInfo
           295  		} else {
           296  			log.Printf("El seguidor %s no respondió al cambio de su timer.", followerInfo.Name)
           297  			l.FailedFollowers[followerInfo.Name] = followerInfo
           298  		}
           299  	}
           300  
           301  	return nil
           302  }
           303  
           304  func (l *Leader) sendTimeUpdateToFollower(follower FollowerInfo, delta int64) *FollowerInfo {
           305  
           306  	// Crear el mapa con la solicitud
           307  	request := DeltaRequest{
           308  		Message:    "Modifica el tiempo del sistema de tu servidor con el diferencial.",
           309  		Operation:  "UPDATE_TIME",
           310  		Delta:      delta,
           311  		LeaderAddr: l.aAbstractNode.Address,
           312  	}
           313  
           314  	// Serializar la solicitud a JSON
           315  	jsonRequest, err := json.Marshal(request)
           316  	if err != nil {
           317  		log.Printf("Error al serializar la solicitud para el seguidor %s: %v", follower.Name, err)
           318  		follower.State = TimeErrorSentUpdate
           319  		return &follower
           320  	}
           321  
           322  	requestString := string(jsonRequest)
           323  	log.Printf("Solicitud enviada a %s: %s", follower.GetAddress(), requestString)
           324  	// Enviar la solicitud
           325  	reply, err := l.aAbstractNode.SendMessageSync(follower.GetAddress(), requestString)
           326  	if err != nil {
           327  		log.Printf("Error al recibir respuesta de %s: %v", follower.GetAddress(), err)
           328  		followError := NewFollowerInfo(follower.GetAddress(), follower.GetName(), 0, 0, 0)
           329  		followError.State = TimeErrorSentUpdate
           330  		return followError
           331  	}
           332  
           333  	var response map[string]string
           334  	err = json.Unmarshal([]byte(reply), &response)
           335  	if err != nil {
           336  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", follower.Name, err)
           337  		follower.State = TimeErrorSentUpdate
           338  		return &follower
           339  	}
           340  
           341  	// Registrar la respuesta
           342  	followerName := response["followerName"]
           343  	operation := response["operation"]
           344  	log.Printf("Respuesta de %s: Operación %s exitosa", followerName, operation)
           345  
           346  	follower.State = TimeUpdated
           347  	return &follower
           348  }
           349  func (l *Leader) sendCloseMessagesToFollowers() {
           350  	// Crear un WaitGroup para esperar a que todas las goroutines terminen
           351  	var wg sync.WaitGroup
           352  
           353  	// Canal para recibir los resultados de las goroutines
           354  	resultCh := make(chan string, len(l.TimeUpdatedFollowers))
           355  
           356  	// Enviar mensaje de cierre a cada seguidor de manera concurrente
           357  	for _, follower := range l.TimeUpdatedFollowers {
           358  		wg.Add(1)
           359  		go func(follower FollowerInfo) {
           360  			defer wg.Done()
           361  
           362  			// Enviar el mensaje de cierre
           363  			err := l.sendCloseMessage(follower.Address, follower.Name)
           364  			if err != nil {
           365  				resultCh <- fmt.Sprintf("Error al enviar mensaje de cierre a %s: %s", follower.Name, err)
           366  				return
           367  			}
           368  
           369  			// Simulamos que el mensaje fue enviado exitosamente
           370  			resultCh <- fmt.Sprintf("Mensaje de cierre enviado con éxito a %s", follower.Name)
           371  		}(*follower)
           372  	}
           373  
           374  	// Esperar a que todas las goroutines terminen
           375  	go func() {
           376  		wg.Wait()
           377  		close(resultCh)
           378  	}()
           379  
           380  	// Procesar los resultados a medida que vayan llegando
           381  	for result := range resultCh {
           382  		log.Println(result)
           383  	}
           384  
           385  }
           386  
           387  // SendCloseMessage envía un mensaje de cierre a un seguidor.
           388  // Simulación de la función para enviar mensaje de cierre a un seguidor
           389  func (l *Leader) sendCloseMessage(followerAddress, followerName string) *FollowerInfo {
           390  	log.Printf("Enviando mensaje de cierre a %s...", followerAddress)
           391  
           392  	request := closeRequest{
           393  		Message:    "Cerrar conexión",
           394  		Operation:  "CLOSE",
           395  		LeaderAddr: l.aAbstractNode.Address,
           396  	}
           397  
           398  	// Convertir el mensaje a JSON
           399  	jsonRequest, err := json.Marshal(request)
           400  	if err != nil {
           401  		log.Printf("error al crear mensaje de cierre: %w", err)
           402  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           403  		followError.State = ErrorClose
           404  		return followError
           405  	}
           406  
           407  	// Simulamos el envío del mensaje al seguidor (usando un canal)
           408  	log.Printf("Mensaje de cierre enviado a %s: %s", followerAddress, jsonRequest)
           409  	// Serializar la solicitud a JSON
           410  
           411  	requestString := string(jsonRequest)
           412  	log.Printf("Solicitud enviada a %s: %s", followerAddress, requestString)
           413  	// Enviar la solicitud
           414  	reply, err := l.aAbstractNode.SendMessageSync(followerAddress, requestString)
           415  	if err != nil {
           416  		log.Printf("Error al recibir respuesta de %s: %v", followerAddress, err)
           417  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           418  		followError.State = ErrorClose
           419  		return followError
           420  	}
           421  
           422  	var response map[string]string
           423  	err = json.Unmarshal([]byte(reply), &response)
           424  	if err != nil {
           425  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", followerName, err)
           426  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           427  		followError.State = ErrorClose
           428  		return followError
           429  	}
           430  	// Simulamos una respuesta (en un caso real recibirías la respuesta desde el socket)
           431  	// Aquí se simula un éxito.
           432  	response = map[string]string{
           433  		"followerName": followerAddress,
           434  		"operation":    "CLOSE",
           435  	}
           436  
           437  	// Convertimos la respuesta a JSON
           438  	jsonResponse, err := json.Marshal(response)
           439  	if err != nil {
           440  		log.Printf("error al procesar la respuesta: %w", err)
           441  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           442  		followError.State = ErrorClose
           443  		return followError
           444  	}
           445  
           446  	// Simulamos la recepción de la respuesta (en un caso real, recibirías el mensaje desde el socket)
           447  	log.Printf("Respuesta recibida de %s: %s", followerAddress, jsonResponse)
           448  	follow := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           449  	follow.State = OkClose
           450  	return follow
           451  }
           452  
           453  // PrintResults muestra los resultados del algoritmo.
           454  func (l *Leader) printResults() {
           455  	l.Logger.Println("Resultados del algoritmo Berkeley:")
           456  
           457  	// Mostrar seguidores inalcanzables
           458  	l.Logger.Println("Seguidores inalcanzables:")
           459  	for key, value := range l.UnreachableFollowers {
           460  		l.Logger.Printf("- %s: %v", key, value)
           461  	}
           462  
           463  	// Mostrar seguidores que no respondieron a tiempo
           464  	l.Logger.Println("Seguidores que no respondieron a tiempo:")
           465  	for key, value := range l.NonRespondingFollowers {
           466  		l.Logger.Printf("- %s: %v", key, value)
           467  	}
           468  
           469  	// Mostrar seguidores que respondieron correctamente
           470  	l.Logger.Println("Seguidores que respondieron correctamente:")
           471  	for key, value := range l.SuccessfulFollowers {
           472  		l.Logger.Printf("- %s: %v", key, value)
           473  	}
           474  
           475  	// Mostrar seguidores que actualizaron su tiempo correctamente
           476  	l.Logger.Println("Seguidores que actualizaron su tiempo correctamente:")
           477  	for key, value := range l.TimeUpdatedFollowers {
           478  		l.Logger.Printf("- %s: %v", key, value)
           479  	}
           480  
           481  	// Mostrar seguidores que no pudieron actualizar su tiempo
           482  	l.Logger.Println("Seguidores que no pudieron actualizar su tiempo:")
           483  	for key, value := range l.FailedFollowers {
           484  		l.Logger.Printf("- %s: %v", key, value)
           485  	}
           486  }
           487  func (l *Leader) Close() {
           488  	l.aAbstractNode.Close()
           489  }
           490  
        

        View as plain text

        src/goberkeley/berkeley/socket_zero_mq_exception.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/socket_zero_mq_exception.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  )
             6  
             7  // ErrorType enum para los diferentes tipos de errores posibles en ZeroMQ.
             8  type ErrorType int
             9  
            10  const (
            11  	// CONNECTION_ERROR Error relacionado con la conexión de ZeroMQ
            12  	CONNECTION_ERROR ErrorType = iota
            13  	// SEND_ERROR Error al enviar un mensaje a través del socket
            14  	SEND_ERROR
            15  	// RECEIVE_ERROR Error al recibir un mensaje del socket
            16  	RECEIVE_ERROR
            17  )
            18  
            19  // SocketZeroMQException estructura que encapsula un error personalizado para ZeroMQ.
            20  type SocketZeroMQException struct {
            21  	Message   string    // Mensaje de error
            22  	ErrorType ErrorType // Tipo de error
            23  }
            24  
            25  // NewSocketZeroMQException crea una nueva instancia de SocketZeroMQException.
            26  func NewSocketZeroMQException(message string, errorType ErrorType) *SocketZeroMQException {
            27  	return &SocketZeroMQException{
            28  		Message:   message,
            29  		ErrorType: errorType,
            30  	}
            31  }
            32  
            33  // Error implementación de la interfaz error para SocketZeroMQException.
            34  func (e *SocketZeroMQException) Error() string {
            35  	return fmt.Sprintf("Error: %s, Tipo de error: %v", e.Message, e.ErrorType)
            36  }
            37  
            38  // GetErrorType obtiene el tipo de error.
            39  func (e *SocketZeroMQException) GetErrorType() ErrorType {
            40  	return e.ErrorType
            41  }
            42  
        

        View as plain text

        src/goberkeley/berkeley/follower.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"errors"
             6  	"fmt"
             7  	"log"
             8  	"time"
             9  )
            10  
            11  // Follower representa un nodo seguidor en el sistema distribuido.
            12  type Follower struct {
            13  	aAbstractNode *AbstractNode
            14  	LeaderAddress string
            15  }
            16  
            17  // InitializeNode inicializa el nodo seguidor con su información específica.
            18  func InitializeFollowerNode(name, address, leaderAddress string, timeout time.Duration) (*Follower, error) {
            19  	// Asegúrate de llamar al método correcto de AbstractNode.
            20  
            21  	f, err := NewFollower(name, address, leaderAddress, timeout)
            22  	if err != nil {
            23  		return nil, err
            24  	}
            25  
            26  	return f, nil
            27  }
            28  
            29  // NewFollower crea e inicializa un nuevo nodo seguidor.
            30  func NewFollower(name, address, leaderAddress string, timeout time.Duration) (*Follower, error) {
            31  	// Inicializar el nodo abstracto usando NewAbstractNode
            32  	abstractNode, err := NewAbstractNode(name, address, timeout)
            33  	if err != nil {
            34  		return nil, err
            35  	}
            36  
            37  	// Crear e inicializar la estructura Follower
            38  	follower := &Follower{
            39  		aAbstractNode: abstractNode,
            40  		LeaderAddress: leaderAddress,
            41  	}
            42  	follower.aAbstractNode.Handler = follower
            43  	return follower, nil
            44  }
            45  
            46  // HandleProcess maneja y procesa los mensajes recibidos del líder.
            47  // Implementación de HandleProcess para Follower
            48  func (f *Follower) HandleProcess(message string) (string, error) {
            49  	log.Printf("Recibiendo mensaje del líder: %s", message) // Traza para ver el mensaje recibido
            50  
            51  	// Deserialización del mensaje JSON
            52  	var data map[string]interface{}
            53  	if err := json.Unmarshal([]byte(message), &data); err != nil {
            54  		log.Printf("Error al deserializar el mensaje JSON: %v", err)
            55  		return `{"error":"Error al procesar el mensaje JSON"}`, nil
            56  	}
            57  	log.Printf("Mensaje deserializado correctamente: %+v", data) // Traza para mostrar el mensaje deserializado
            58  
            59  	// Extraer los campos del mensaje deserializado
            60  	leaderAddr := data["leader_address"].(string)
            61  	operation := data["operation"].(string)
            62  	leaderMessage := data["message"].(string)
            63  
            64  	log.Printf("Procesando mensaje del líder: %s desde %s con operación: %s", leaderAddr, f.LeaderAddress, operation)
            65  
            66  	// Procesar según la operación especificada
            67  	switch operation {
            68  	case "GET_TIME":
            69  		// Acceder a 'time' y asegurar su tipo como float64
            70  		T0Float, ok := data["time"].(float64)
            71  		if !ok {
            72  			log.Printf("Error al convertir data[\"time\"] a float64")
            73  			return "", errors.New("Error al procesar el campo Time")
            74  		}
            75  
            76  		// Convertir de float64 a int64
            77  		T0 := int64(T0Float)
            78  
            79  		log.Printf("T0 recibido: %d", T0)
            80  		currentTime := f.getCurrentTime()
            81  
            82  		log.Printf("Operación GET_TIME: T0 recibido %d, Hora local calculada: %d", T0, currentTime) // Traza para tiempo
            83  
            84  		// Llamada a la función que maneja el mensaje del líder y muestra su mensaje
            85  		TP := f.displayLeaderMessage(leaderAddr, leaderMessage, T0, currentTime)
            86  		log.Printf("Hora procesada TP: %d", TP) // Traza para TP
            87  
            88  		// Responder con el formato esperado
            89  		return fmt.Sprintf(`{"followerName":"%s", "localTime":"%d", "addressFollower":"%s"}`, f.aAbstractNode.Name, TP, f.aAbstractNode.Address), nil
            90  	case "UPDATE_TIME":
            91  		delta := int64(data["delta"].(float64))
            92  		log.Printf("Operación UPDATE_TIME: Delta recibido: %d", delta) // Traza para delta
            93  
            94  		// Modificar el sistema según el delta
            95  		return f.modSystemTime(delta), nil
            96  	case "CLOSE":
            97  		log.Printf("Operación CLOSE: Cerrando seguidor %s", f.aAbstractNode.Name) // Traza para CLOSE
            98  		return fmt.Sprintf(`{"followerName":"%s","operation":"CLOSE"}`, f.aAbstractNode.Name), nil
            99  	default:
           100  		log.Printf("Operación no reconocida en el mensaje del líder: %s", operation) // Traza para operación no reconocida
           101  		return `{"error":"Operación no reconocida"}`, nil
           102  	}
           103  }
           104  
           105  // displayLeaderMessage muestra el mensaje del líder y calcula un tiempo promedio (TP).
           106  func (f *Follower) displayLeaderMessage(leaderAddr, leaderMessage string, T0, localTime int64) int64 {
           107  	log.Printf("Mensaje del líder con dirección (%s) recibido: %s con T0 %s", leaderAddr, leaderMessage, time.UnixMilli(T0).String())
           108  	TP := (T0 + localTime) / 2
           109  	log.Printf("TP del seguidor %s es %s", f.aAbstractNode.Name, time.UnixMilli(TP).String())
           110  	return TP
           111  }
           112  
           113  // modSystemTime modifica el tiempo local del sistema basado en un delta.
           114  func (f *Follower) modSystemTime(delta int64) string {
           115  	currentLocalTime := time.Now().UnixMilli()
           116  	modSystemTime := currentLocalTime + delta
           117  	log.Printf("Tiempo del seguidor %s modificado de %s a %s", f.aAbstractNode.Name, time.UnixMilli(currentLocalTime).String(), time.UnixMilli(modSystemTime).String())
           118  	return fmt.Sprintf(`{"followerName":"%s", "localTime":"%d","operation":"OK_MOD_TIME"}`, f.aAbstractNode.Name, modSystemTime)
           119  }
           120  
           121  // getCurrentTime obtiene la hora actual del sistema en milisegundos desde la época Unix.
           122  func (f *Follower) getCurrentTime() int64 {
           123  	TP := time.Now().UnixMilli()
           124  	log.Printf("Fecha y hora local del seguidor: TP: %s", time.UnixMilli(TP).String())
           125  	return TP
           126  }
           127  
           128  // StartAlgorithm configura e inicia el socket REP para escuchar mensajes entrantes
           129  // y delega la responsabilidad de iniciar la escucha al nodo abstracto.
           130  // StartAlgorithm configura e inicia la escucha en el seguidor
           131  func (f *Follower) StartAlgorithm() error {
           132  	// Llama a StartListening, que se encargará de la creación y enlace del socket.
           133  	log.Printf("Iniciando algoritmo para el seguidor %s en %s", f.aAbstractNode.Name, f.aAbstractNode.Address)
           134  	return f.aAbstractNode.StartListening()
           135  }
           136  
        

        View as plain text

        src/goberkeley/berkeley/follower.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"errors"
             6  	"fmt"
             7  	"log"
             8  	"time"
             9  )
            10  
            11  // Follower representa un nodo seguidor en el sistema distribuido.
            12  type Follower struct {
            13  	aAbstractNode *AbstractNode
            14  	LeaderAddress string
            15  }
            16  
            17  // InitializeNode inicializa el nodo seguidor con su información específica.
            18  func InitializeFollowerNode(name, address, leaderAddress string, timeout time.Duration) (*Follower, error) {
            19  	// Asegúrate de llamar al método correcto de AbstractNode.
            20  
            21  	f, err := NewFollower(name, address, leaderAddress, timeout)
            22  	if err != nil {
            23  		return nil, err
            24  	}
            25  
            26  	return f, nil
            27  }
            28  
            29  // NewFollower crea e inicializa un nuevo nodo seguidor.
            30  func NewFollower(name, address, leaderAddress string, timeout time.Duration) (*Follower, error) {
            31  	// Inicializar el nodo abstracto usando NewAbstractNode
            32  	abstractNode, err := NewAbstractNode(name, address, timeout)
            33  	if err != nil {
            34  		return nil, err
            35  	}
            36  
            37  	// Crear e inicializar la estructura Follower
            38  	follower := &Follower{
            39  		aAbstractNode: abstractNode,
            40  		LeaderAddress: leaderAddress,
            41  	}
            42  	follower.aAbstractNode.Handler = follower
            43  	return follower, nil
            44  }
            45  
            46  // HandleProcess maneja y procesa los mensajes recibidos del líder.
            47  // Implementación de HandleProcess para Follower
            48  func (f *Follower) HandleProcess(message string) (string, error) {
            49  	log.Printf("Recibiendo mensaje del líder: %s", message) // Traza para ver el mensaje recibido
            50  
            51  	// Deserialización del mensaje JSON
            52  	var data map[string]interface{}
            53  	if err := json.Unmarshal([]byte(message), &data); err != nil {
            54  		log.Printf("Error al deserializar el mensaje JSON: %v", err)
            55  		return `{"error":"Error al procesar el mensaje JSON"}`, nil
            56  	}
            57  	log.Printf("Mensaje deserializado correctamente: %+v", data) // Traza para mostrar el mensaje deserializado
            58  
            59  	// Extraer los campos del mensaje deserializado
            60  	leaderAddr := data["leader_address"].(string)
            61  	operation := data["operation"].(string)
            62  	leaderMessage := data["message"].(string)
            63  
            64  	log.Printf("Procesando mensaje del líder: %s desde %s con operación: %s", leaderAddr, f.LeaderAddress, operation)
            65  
            66  	// Procesar según la operación especificada
            67  	switch operation {
            68  	case "GET_TIME":
            69  		// Acceder a 'time' y asegurar su tipo como float64
            70  		T0Float, ok := data["time"].(float64)
            71  		if !ok {
            72  			log.Printf("Error al convertir data[\"time\"] a float64")
            73  			return "", errors.New("Error al procesar el campo Time")
            74  		}
            75  
            76  		// Convertir de float64 a int64
            77  		T0 := int64(T0Float)
            78  
            79  		log.Printf("T0 recibido: %d", T0)
            80  		currentTime := f.getCurrentTime()
            81  
            82  		log.Printf("Operación GET_TIME: T0 recibido %d, Hora local calculada: %d", T0, currentTime) // Traza para tiempo
            83  
            84  		// Llamada a la función que maneja el mensaje del líder y muestra su mensaje
            85  		TP := f.displayLeaderMessage(leaderAddr, leaderMessage, T0, currentTime)
            86  		log.Printf("Hora procesada TP: %d", TP) // Traza para TP
            87  
            88  		// Responder con el formato esperado
            89  		return fmt.Sprintf(`{"followerName":"%s", "localTime":"%d", "addressFollower":"%s"}`, f.aAbstractNode.Name, TP, f.aAbstractNode.Address), nil
            90  	case "UPDATE_TIME":
            91  		delta := int64(data["delta"].(float64))
            92  		log.Printf("Operación UPDATE_TIME: Delta recibido: %d", delta) // Traza para delta
            93  
            94  		// Modificar el sistema según el delta
            95  		return f.modSystemTime(delta), nil
            96  	case "CLOSE":
            97  		log.Printf("Operación CLOSE: Cerrando seguidor %s", f.aAbstractNode.Name) // Traza para CLOSE
            98  		return fmt.Sprintf(`{"followerName":"%s","operation":"CLOSE"}`, f.aAbstractNode.Name), nil
            99  	default:
           100  		log.Printf("Operación no reconocida en el mensaje del líder: %s", operation) // Traza para operación no reconocida
           101  		return `{"error":"Operación no reconocida"}`, nil
           102  	}
           103  }
           104  
           105  // displayLeaderMessage muestra el mensaje del líder y calcula un tiempo promedio (TP).
           106  func (f *Follower) displayLeaderMessage(leaderAddr, leaderMessage string, T0, localTime int64) int64 {
           107  	log.Printf("Mensaje del líder con dirección (%s) recibido: %s con T0 %s", leaderAddr, leaderMessage, time.UnixMilli(T0).String())
           108  	TP := (T0 + localTime) / 2
           109  	log.Printf("TP del seguidor %s es %s", f.aAbstractNode.Name, time.UnixMilli(TP).String())
           110  	return TP
           111  }
           112  
           113  // modSystemTime modifica el tiempo local del sistema basado en un delta.
           114  func (f *Follower) modSystemTime(delta int64) string {
           115  	currentLocalTime := time.Now().UnixMilli()
           116  	modSystemTime := currentLocalTime + delta
           117  	log.Printf("Tiempo del seguidor %s modificado de %s a %s", f.aAbstractNode.Name, time.UnixMilli(currentLocalTime).String(), time.UnixMilli(modSystemTime).String())
           118  	return fmt.Sprintf(`{"followerName":"%s", "localTime":"%d","operation":"OK_MOD_TIME"}`, f.aAbstractNode.Name, modSystemTime)
           119  }
           120  
           121  // getCurrentTime obtiene la hora actual del sistema en milisegundos desde la época Unix.
           122  func (f *Follower) getCurrentTime() int64 {
           123  	TP := time.Now().UnixMilli()
           124  	log.Printf("Fecha y hora local del seguidor: TP: %s", time.UnixMilli(TP).String())
           125  	return TP
           126  }
           127  
           128  // StartAlgorithm configura e inicia el socket REP para escuchar mensajes entrantes
           129  // y delega la responsabilidad de iniciar la escucha al nodo abstracto.
           130  // StartAlgorithm configura e inicia la escucha en el seguidor
           131  func (f *Follower) StartAlgorithm() error {
           132  	// Llama a StartListening, que se encargará de la creación y enlace del socket.
           133  	log.Printf("Iniciando algoritmo para el seguidor %s en %s", f.aAbstractNode.Name, f.aAbstractNode.Address)
           134  	return f.aAbstractNode.StartListening()
           135  }
           136  
        

        View as plain text

        src/goberkeley/berkeley/follower.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"errors"
             6  	"fmt"
             7  	"log"
             8  	"time"
             9  )
            10  
            11  // Follower representa un nodo seguidor en el sistema distribuido.
            12  type Follower struct {
            13  	aAbstractNode *AbstractNode
            14  	LeaderAddress string
            15  }
            16  
            17  // InitializeNode inicializa el nodo seguidor con su información específica.
            18  func InitializeFollowerNode(name, address, leaderAddress string, timeout time.Duration) (*Follower, error) {
            19  	// Asegúrate de llamar al método correcto de AbstractNode.
            20  
            21  	f, err := NewFollower(name, address, leaderAddress, timeout)
            22  	if err != nil {
            23  		return nil, err
            24  	}
            25  
            26  	return f, nil
            27  }
            28  
            29  // NewFollower crea e inicializa un nuevo nodo seguidor.
            30  func NewFollower(name, address, leaderAddress string, timeout time.Duration) (*Follower, error) {
            31  	// Inicializar el nodo abstracto usando NewAbstractNode
            32  	abstractNode, err := NewAbstractNode(name, address, timeout)
            33  	if err != nil {
            34  		return nil, err
            35  	}
            36  
            37  	// Crear e inicializar la estructura Follower
            38  	follower := &Follower{
            39  		aAbstractNode: abstractNode,
            40  		LeaderAddress: leaderAddress,
            41  	}
            42  	follower.aAbstractNode.Handler = follower
            43  	return follower, nil
            44  }
            45  
            46  // HandleProcess maneja y procesa los mensajes recibidos del líder.
            47  // Implementación de HandleProcess para Follower
            48  func (f *Follower) HandleProcess(message string) (string, error) {
            49  	log.Printf("Recibiendo mensaje del líder: %s", message) // Traza para ver el mensaje recibido
            50  
            51  	// Deserialización del mensaje JSON
            52  	var data map[string]interface{}
            53  	if err := json.Unmarshal([]byte(message), &data); err != nil {
            54  		log.Printf("Error al deserializar el mensaje JSON: %v", err)
            55  		return `{"error":"Error al procesar el mensaje JSON"}`, nil
            56  	}
            57  	log.Printf("Mensaje deserializado correctamente: %+v", data) // Traza para mostrar el mensaje deserializado
            58  
            59  	// Extraer los campos del mensaje deserializado
            60  	leaderAddr := data["leader_address"].(string)
            61  	operation := data["operation"].(string)
            62  	leaderMessage := data["message"].(string)
            63  
            64  	log.Printf("Procesando mensaje del líder: %s desde %s con operación: %s", leaderAddr, f.LeaderAddress, operation)
            65  
            66  	// Procesar según la operación especificada
            67  	switch operation {
            68  	case "GET_TIME":
            69  		// Acceder a 'time' y asegurar su tipo como float64
            70  		T0Float, ok := data["time"].(float64)
            71  		if !ok {
            72  			log.Printf("Error al convertir data[\"time\"] a float64")
            73  			return "", errors.New("Error al procesar el campo Time")
            74  		}
            75  
            76  		// Convertir de float64 a int64
            77  		T0 := int64(T0Float)
            78  
            79  		log.Printf("T0 recibido: %d", T0)
            80  		currentTime := f.getCurrentTime()
            81  
            82  		log.Printf("Operación GET_TIME: T0 recibido %d, Hora local calculada: %d", T0, currentTime) // Traza para tiempo
            83  
            84  		// Llamada a la función que maneja el mensaje del líder y muestra su mensaje
            85  		TP := f.displayLeaderMessage(leaderAddr, leaderMessage, T0, currentTime)
            86  		log.Printf("Hora procesada TP: %d", TP) // Traza para TP
            87  
            88  		// Responder con el formato esperado
            89  		return fmt.Sprintf(`{"followerName":"%s", "localTime":"%d", "addressFollower":"%s"}`, f.aAbstractNode.Name, TP, f.aAbstractNode.Address), nil
            90  	case "UPDATE_TIME":
            91  		delta := int64(data["delta"].(float64))
            92  		log.Printf("Operación UPDATE_TIME: Delta recibido: %d", delta) // Traza para delta
            93  
            94  		// Modificar el sistema según el delta
            95  		return f.modSystemTime(delta), nil
            96  	case "CLOSE":
            97  		log.Printf("Operación CLOSE: Cerrando seguidor %s", f.aAbstractNode.Name) // Traza para CLOSE
            98  		return fmt.Sprintf(`{"followerName":"%s","operation":"CLOSE"}`, f.aAbstractNode.Name), nil
            99  	default:
           100  		log.Printf("Operación no reconocida en el mensaje del líder: %s", operation) // Traza para operación no reconocida
           101  		return `{"error":"Operación no reconocida"}`, nil
           102  	}
           103  }
           104  
           105  // displayLeaderMessage muestra el mensaje del líder y calcula un tiempo promedio (TP).
           106  func (f *Follower) displayLeaderMessage(leaderAddr, leaderMessage string, T0, localTime int64) int64 {
           107  	log.Printf("Mensaje del líder con dirección (%s) recibido: %s con T0 %s", leaderAddr, leaderMessage, time.UnixMilli(T0).String())
           108  	TP := (T0 + localTime) / 2
           109  	log.Printf("TP del seguidor %s es %s", f.aAbstractNode.Name, time.UnixMilli(TP).String())
           110  	return TP
           111  }
           112  
           113  // modSystemTime modifica el tiempo local del sistema basado en un delta.
           114  func (f *Follower) modSystemTime(delta int64) string {
           115  	currentLocalTime := time.Now().UnixMilli()
           116  	modSystemTime := currentLocalTime + delta
           117  	log.Printf("Tiempo del seguidor %s modificado de %s a %s", f.aAbstractNode.Name, time.UnixMilli(currentLocalTime).String(), time.UnixMilli(modSystemTime).String())
           118  	return fmt.Sprintf(`{"followerName":"%s", "localTime":"%d","operation":"OK_MOD_TIME"}`, f.aAbstractNode.Name, modSystemTime)
           119  }
           120  
           121  // getCurrentTime obtiene la hora actual del sistema en milisegundos desde la época Unix.
           122  func (f *Follower) getCurrentTime() int64 {
           123  	TP := time.Now().UnixMilli()
           124  	log.Printf("Fecha y hora local del seguidor: TP: %s", time.UnixMilli(TP).String())
           125  	return TP
           126  }
           127  
           128  // StartAlgorithm configura e inicia el socket REP para escuchar mensajes entrantes
           129  // y delega la responsabilidad de iniciar la escucha al nodo abstracto.
           130  // StartAlgorithm configura e inicia la escucha en el seguidor
           131  func (f *Follower) StartAlgorithm() error {
           132  	// Llama a StartListening, que se encargará de la creación y enlace del socket.
           133  	log.Printf("Iniciando algoritmo para el seguidor %s en %s", f.aAbstractNode.Name, f.aAbstractNode.Address)
           134  	return f.aAbstractNode.StartListening()
           135  }
           136  
        

        View as plain text

        src/goberkeley/berkeley/follower.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"errors"
             6  	"fmt"
             7  	"log"
             8  	"time"
             9  )
            10  
            11  // Follower representa un nodo seguidor en el sistema distribuido.
            12  type Follower struct {
            13  	aAbstractNode *AbstractNode
            14  	LeaderAddress string
            15  }
            16  
            17  // InitializeNode inicializa el nodo seguidor con su información específica.
            18  func InitializeFollowerNode(name, address, leaderAddress string, timeout time.Duration) (*Follower, error) {
            19  	// Asegúrate de llamar al método correcto de AbstractNode.
            20  
            21  	f, err := NewFollower(name, address, leaderAddress, timeout)
            22  	if err != nil {
            23  		return nil, err
            24  	}
            25  
            26  	return f, nil
            27  }
            28  
            29  // NewFollower crea e inicializa un nuevo nodo seguidor.
            30  func NewFollower(name, address, leaderAddress string, timeout time.Duration) (*Follower, error) {
            31  	// Inicializar el nodo abstracto usando NewAbstractNode
            32  	abstractNode, err := NewAbstractNode(name, address, timeout)
            33  	if err != nil {
            34  		return nil, err
            35  	}
            36  
            37  	// Crear e inicializar la estructura Follower
            38  	follower := &Follower{
            39  		aAbstractNode: abstractNode,
            40  		LeaderAddress: leaderAddress,
            41  	}
            42  	follower.aAbstractNode.Handler = follower
            43  	return follower, nil
            44  }
            45  
            46  // HandleProcess maneja y procesa los mensajes recibidos del líder.
            47  // Implementación de HandleProcess para Follower
            48  func (f *Follower) HandleProcess(message string) (string, error) {
            49  	log.Printf("Recibiendo mensaje del líder: %s", message) // Traza para ver el mensaje recibido
            50  
            51  	// Deserialización del mensaje JSON
            52  	var data map[string]interface{}
            53  	if err := json.Unmarshal([]byte(message), &data); err != nil {
            54  		log.Printf("Error al deserializar el mensaje JSON: %v", err)
            55  		return `{"error":"Error al procesar el mensaje JSON"}`, nil
            56  	}
            57  	log.Printf("Mensaje deserializado correctamente: %+v", data) // Traza para mostrar el mensaje deserializado
            58  
            59  	// Extraer los campos del mensaje deserializado
            60  	leaderAddr := data["leader_address"].(string)
            61  	operation := data["operation"].(string)
            62  	leaderMessage := data["message"].(string)
            63  
            64  	log.Printf("Procesando mensaje del líder: %s desde %s con operación: %s", leaderAddr, f.LeaderAddress, operation)
            65  
            66  	// Procesar según la operación especificada
            67  	switch operation {
            68  	case "GET_TIME":
            69  		// Acceder a 'time' y asegurar su tipo como float64
            70  		T0Float, ok := data["time"].(float64)
            71  		if !ok {
            72  			log.Printf("Error al convertir data[\"time\"] a float64")
            73  			return "", errors.New("Error al procesar el campo Time")
            74  		}
            75  
            76  		// Convertir de float64 a int64
            77  		T0 := int64(T0Float)
            78  
            79  		log.Printf("T0 recibido: %d", T0)
            80  		currentTime := f.getCurrentTime()
            81  
            82  		log.Printf("Operación GET_TIME: T0 recibido %d, Hora local calculada: %d", T0, currentTime) // Traza para tiempo
            83  
            84  		// Llamada a la función que maneja el mensaje del líder y muestra su mensaje
            85  		TP := f.displayLeaderMessage(leaderAddr, leaderMessage, T0, currentTime)
            86  		log.Printf("Hora procesada TP: %d", TP) // Traza para TP
            87  
            88  		// Responder con el formato esperado
            89  		return fmt.Sprintf(`{"followerName":"%s", "localTime":"%d", "addressFollower":"%s"}`, f.aAbstractNode.Name, TP, f.aAbstractNode.Address), nil
            90  	case "UPDATE_TIME":
            91  		delta := int64(data["delta"].(float64))
            92  		log.Printf("Operación UPDATE_TIME: Delta recibido: %d", delta) // Traza para delta
            93  
            94  		// Modificar el sistema según el delta
            95  		return f.modSystemTime(delta), nil
            96  	case "CLOSE":
            97  		log.Printf("Operación CLOSE: Cerrando seguidor %s", f.aAbstractNode.Name) // Traza para CLOSE
            98  		return fmt.Sprintf(`{"followerName":"%s","operation":"CLOSE"}`, f.aAbstractNode.Name), nil
            99  	default:
           100  		log.Printf("Operación no reconocida en el mensaje del líder: %s", operation) // Traza para operación no reconocida
           101  		return `{"error":"Operación no reconocida"}`, nil
           102  	}
           103  }
           104  
           105  // displayLeaderMessage muestra el mensaje del líder y calcula un tiempo promedio (TP).
           106  func (f *Follower) displayLeaderMessage(leaderAddr, leaderMessage string, T0, localTime int64) int64 {
           107  	log.Printf("Mensaje del líder con dirección (%s) recibido: %s con T0 %s", leaderAddr, leaderMessage, time.UnixMilli(T0).String())
           108  	TP := (T0 + localTime) / 2
           109  	log.Printf("TP del seguidor %s es %s", f.aAbstractNode.Name, time.UnixMilli(TP).String())
           110  	return TP
           111  }
           112  
           113  // modSystemTime modifica el tiempo local del sistema basado en un delta.
           114  func (f *Follower) modSystemTime(delta int64) string {
           115  	currentLocalTime := time.Now().UnixMilli()
           116  	modSystemTime := currentLocalTime + delta
           117  	log.Printf("Tiempo del seguidor %s modificado de %s a %s", f.aAbstractNode.Name, time.UnixMilli(currentLocalTime).String(), time.UnixMilli(modSystemTime).String())
           118  	return fmt.Sprintf(`{"followerName":"%s", "localTime":"%d","operation":"OK_MOD_TIME"}`, f.aAbstractNode.Name, modSystemTime)
           119  }
           120  
           121  // getCurrentTime obtiene la hora actual del sistema en milisegundos desde la época Unix.
           122  func (f *Follower) getCurrentTime() int64 {
           123  	TP := time.Now().UnixMilli()
           124  	log.Printf("Fecha y hora local del seguidor: TP: %s", time.UnixMilli(TP).String())
           125  	return TP
           126  }
           127  
           128  // StartAlgorithm configura e inicia el socket REP para escuchar mensajes entrantes
           129  // y delega la responsabilidad de iniciar la escucha al nodo abstracto.
           130  // StartAlgorithm configura e inicia la escucha en el seguidor
           131  func (f *Follower) StartAlgorithm() error {
           132  	// Llama a StartListening, que se encargará de la creación y enlace del socket.
           133  	log.Printf("Iniciando algoritmo para el seguidor %s en %s", f.aAbstractNode.Name, f.aAbstractNode.Address)
           134  	return f.aAbstractNode.StartListening()
           135  }
           136  
        

        View as plain text

        src/goberkeley/berkeley/follower.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"errors"
             6  	"fmt"
             7  	"log"
             8  	"time"
             9  )
            10  
            11  // Follower representa un nodo seguidor en el sistema distribuido.
            12  type Follower struct {
            13  	aAbstractNode *AbstractNode
            14  	LeaderAddress string
            15  }
            16  
            17  // InitializeNode inicializa el nodo seguidor con su información específica.
            18  func InitializeFollowerNode(name, address, leaderAddress string, timeout time.Duration) (*Follower, error) {
            19  	// Asegúrate de llamar al método correcto de AbstractNode.
            20  
            21  	f, err := NewFollower(name, address, leaderAddress, timeout)
            22  	if err != nil {
            23  		return nil, err
            24  	}
            25  
            26  	return f, nil
            27  }
            28  
            29  // NewFollower crea e inicializa un nuevo nodo seguidor.
            30  func NewFollower(name, address, leaderAddress string, timeout time.Duration) (*Follower, error) {
            31  	// Inicializar el nodo abstracto usando NewAbstractNode
            32  	abstractNode, err := NewAbstractNode(name, address, timeout)
            33  	if err != nil {
            34  		return nil, err
            35  	}
            36  
            37  	// Crear e inicializar la estructura Follower
            38  	follower := &Follower{
            39  		aAbstractNode: abstractNode,
            40  		LeaderAddress: leaderAddress,
            41  	}
            42  	follower.aAbstractNode.Handler = follower
            43  	return follower, nil
            44  }
            45  
            46  // HandleProcess maneja y procesa los mensajes recibidos del líder.
            47  // Implementación de HandleProcess para Follower
            48  func (f *Follower) HandleProcess(message string) (string, error) {
            49  	log.Printf("Recibiendo mensaje del líder: %s", message) // Traza para ver el mensaje recibido
            50  
            51  	// Deserialización del mensaje JSON
            52  	var data map[string]interface{}
            53  	if err := json.Unmarshal([]byte(message), &data); err != nil {
            54  		log.Printf("Error al deserializar el mensaje JSON: %v", err)
            55  		return `{"error":"Error al procesar el mensaje JSON"}`, nil
            56  	}
            57  	log.Printf("Mensaje deserializado correctamente: %+v", data) // Traza para mostrar el mensaje deserializado
            58  
            59  	// Extraer los campos del mensaje deserializado
            60  	leaderAddr := data["leader_address"].(string)
            61  	operation := data["operation"].(string)
            62  	leaderMessage := data["message"].(string)
            63  
            64  	log.Printf("Procesando mensaje del líder: %s desde %s con operación: %s", leaderAddr, f.LeaderAddress, operation)
            65  
            66  	// Procesar según la operación especificada
            67  	switch operation {
            68  	case "GET_TIME":
            69  		// Acceder a 'time' y asegurar su tipo como float64
            70  		T0Float, ok := data["time"].(float64)
            71  		if !ok {
            72  			log.Printf("Error al convertir data[\"time\"] a float64")
            73  			return "", errors.New("Error al procesar el campo Time")
            74  		}
            75  
            76  		// Convertir de float64 a int64
            77  		T0 := int64(T0Float)
            78  
            79  		log.Printf("T0 recibido: %d", T0)
            80  		currentTime := f.getCurrentTime()
            81  
            82  		log.Printf("Operación GET_TIME: T0 recibido %d, Hora local calculada: %d", T0, currentTime) // Traza para tiempo
            83  
            84  		// Llamada a la función que maneja el mensaje del líder y muestra su mensaje
            85  		TP := f.displayLeaderMessage(leaderAddr, leaderMessage, T0, currentTime)
            86  		log.Printf("Hora procesada TP: %d", TP) // Traza para TP
            87  
            88  		// Responder con el formato esperado
            89  		return fmt.Sprintf(`{"followerName":"%s", "localTime":"%d", "addressFollower":"%s"}`, f.aAbstractNode.Name, TP, f.aAbstractNode.Address), nil
            90  	case "UPDATE_TIME":
            91  		delta := int64(data["delta"].(float64))
            92  		log.Printf("Operación UPDATE_TIME: Delta recibido: %d", delta) // Traza para delta
            93  
            94  		// Modificar el sistema según el delta
            95  		return f.modSystemTime(delta), nil
            96  	case "CLOSE":
            97  		log.Printf("Operación CLOSE: Cerrando seguidor %s", f.aAbstractNode.Name) // Traza para CLOSE
            98  		return fmt.Sprintf(`{"followerName":"%s","operation":"CLOSE"}`, f.aAbstractNode.Name), nil
            99  	default:
           100  		log.Printf("Operación no reconocida en el mensaje del líder: %s", operation) // Traza para operación no reconocida
           101  		return `{"error":"Operación no reconocida"}`, nil
           102  	}
           103  }
           104  
           105  // displayLeaderMessage muestra el mensaje del líder y calcula un tiempo promedio (TP).
           106  func (f *Follower) displayLeaderMessage(leaderAddr, leaderMessage string, T0, localTime int64) int64 {
           107  	log.Printf("Mensaje del líder con dirección (%s) recibido: %s con T0 %s", leaderAddr, leaderMessage, time.UnixMilli(T0).String())
           108  	TP := (T0 + localTime) / 2
           109  	log.Printf("TP del seguidor %s es %s", f.aAbstractNode.Name, time.UnixMilli(TP).String())
           110  	return TP
           111  }
           112  
           113  // modSystemTime modifica el tiempo local del sistema basado en un delta.
           114  func (f *Follower) modSystemTime(delta int64) string {
           115  	currentLocalTime := time.Now().UnixMilli()
           116  	modSystemTime := currentLocalTime + delta
           117  	log.Printf("Tiempo del seguidor %s modificado de %s a %s", f.aAbstractNode.Name, time.UnixMilli(currentLocalTime).String(), time.UnixMilli(modSystemTime).String())
           118  	return fmt.Sprintf(`{"followerName":"%s", "localTime":"%d","operation":"OK_MOD_TIME"}`, f.aAbstractNode.Name, modSystemTime)
           119  }
           120  
           121  // getCurrentTime obtiene la hora actual del sistema en milisegundos desde la época Unix.
           122  func (f *Follower) getCurrentTime() int64 {
           123  	TP := time.Now().UnixMilli()
           124  	log.Printf("Fecha y hora local del seguidor: TP: %s", time.UnixMilli(TP).String())
           125  	return TP
           126  }
           127  
           128  // StartAlgorithm configura e inicia el socket REP para escuchar mensajes entrantes
           129  // y delega la responsabilidad de iniciar la escucha al nodo abstracto.
           130  // StartAlgorithm configura e inicia la escucha en el seguidor
           131  func (f *Follower) StartAlgorithm() error {
           132  	// Llama a StartListening, que se encargará de la creación y enlace del socket.
           133  	log.Printf("Iniciando algoritmo para el seguidor %s en %s", f.aAbstractNode.Name, f.aAbstractNode.Address)
           134  	return f.aAbstractNode.StartListening()
           135  }
           136  
        

        View as plain text

        src/goberkeley/berkeley/config.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/config.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  	"os"
             7  	"time"
             8  )
             9  
            10  type LeaderConfig struct {
            11  	Name    string `json:"name"`
            12  	Address string `json:"address"`
            13  }
            14  
            15  type FollowerConfig struct {
            16  	Name    string `json:"name"`
            17  	Address string `json:"address"`
            18  }
            19  
            20  type Config struct {
            21  	Leader    LeaderConfig     `json:"leader"`
            22  	Followers []FollowerConfig `json:"followers"`
            23  	Timeout   time.Duration    `json:"timeout"`
            24  }
            25  
            26  func LoadConfig(filepath string) *Config {
            27  	// Abrir el archivo JSON
            28  	file, err := os.Open(filepath)
            29  	if err != nil {
            30  		fmt.Println("Error abriendo el archivo:", err)
            31  		return nil
            32  	}
            33  	defer file.Close()
            34  
            35  	// Decodificar el JSON en la estructura Config
            36  	var config Config
            37  	decoder := json.NewDecoder(file)
            38  	if err := decoder.Decode(&config); err != nil {
            39  		fmt.Println("Error decodificando JSON:", err)
            40  		return nil
            41  	}
            42  
            43  	// Imprimir la configuración cargada
            44  	fmt.Printf("Líder: %s (%s)\n", config.Leader.Name, config.Leader.Address)
            45  	for _, follower := range config.Followers {
            46  		fmt.Printf("Seguidor: %s (%s)\n", follower.Name, follower.Address)
            47  	}
            48  	fmt.Printf("Timeout: %d ms\n", config.Timeout)
            49  
            50  	return &config
            51  }
            52  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_info.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_info.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  	"time"
             6  )
             7  
             8  // FollowerInfo encapsula información sobre un nodo seguidor en el sistema.
             9  type FollowerInfo struct {
            10  	Name              string        // Nombre del seguidor
            11  	Address           string        // Dirección del seguidor en formato "host:puerto"
            12  	State             FollowerState // Estado actual del seguidor
            13  	DateFollower      time.Time     // Fecha y hora local del seguidor
            14  	LocalTime         int64         // Hora local del seguidor en milisegundos desde la época UNIX
            15  	CommunicationTime int64         // Tiempo de comunicación entre líder y seguidor en milisegundos
            16  	TripTime          int64         // Tiempo de ida y vuelta (triptime) estimado
            17  	DiffTime          int64         // Diferencia de tiempo calculada entre líder y seguidor
            18  	Delta             int64         // Diferencia global de tiempo (delta) aplicada al seguidor
            19  }
            20  
            21  // NewFollowerInfo crea un nuevo objeto FollowerInfo con los valores proporcionados.
            22  func NewFollowerInfo(address, name string, localTime, communicationTime, nowTime int64) *FollowerInfo {
            23  	tripTime := communicationTime / 2
            24  	diffTime := (localTime + tripTime) - nowTime
            25  
            26  	return &FollowerInfo{
            27  		Name:              name,
            28  		Address:           address,
            29  		LocalTime:         localTime,
            30  		CommunicationTime: communicationTime,
            31  		TripTime:          tripTime,
            32  		DiffTime:          diffTime,
            33  		State:             RequestNotSent, // Estado inicial por defecto
            34  	}
            35  }
            36  
            37  // GetAddress devuelve la dirección del seguidor.
            38  func (f *FollowerInfo) GetAddress() string {
            39  	return f.Address
            40  }
            41  
            42  // GetName devuelve el nombre del seguidor.
            43  func (f *FollowerInfo) GetName() string {
            44  	return f.Name
            45  }
            46  
            47  // GetDateFollower devuelve la fecha y hora local del seguidor.
            48  func (f *FollowerInfo) GetDateFollower() time.Time {
            49  	return f.DateFollower
            50  }
            51  
            52  // GetDiffTime devuelve la diferencia de tiempo entre el líder y el seguidor.
            53  func (f *FollowerInfo) GetDiffTime() int64 {
            54  	return f.DiffTime
            55  }
            56  
            57  // GetLocalTime devuelve la hora local del seguidor.
            58  func (f *FollowerInfo) GetLocalTime() int64 {
            59  	return f.LocalTime
            60  }
            61  
            62  // GetCommunicationTime devuelve el tiempo de comunicación entre líder y seguidor.
            63  func (f *FollowerInfo) GetCommunicationTime() int64 {
            64  	return f.CommunicationTime
            65  }
            66  
            67  // GetDelta devuelve la diferencia global de tiempo (delta).
            68  func (f *FollowerInfo) GetDelta() int64 {
            69  	return f.Delta
            70  }
            71  
            72  // SetDelta establece la diferencia global de tiempo (delta) para el seguidor.
            73  func (f *FollowerInfo) SetDelta(delta int64) {
            74  	f.Delta = delta
            75  }
            76  
            77  // GetState devuelve el estado actual del seguidor.
            78  func (f *FollowerInfo) GetState() FollowerState {
            79  	return f.State
            80  }
            81  
            82  // SetState establece el estado del seguidor.
            83  func (f *FollowerInfo) SetState(state FollowerState) {
            84  	f.State = state
            85  }
            86  
            87  // String genera una representación en cadena del objeto FollowerInfo.
            88  func (f *FollowerInfo) String() string {
            89  	return fmt.Sprintf("Nombre: %s, Estado: %s, Hora local: %d, Fecha: %s, "+
            90  		"Tiempo de comunicación: %d ms, TripTime: %d ms, Diferencia de tiempo: %d ms, "+
            91  		"Diferencia global (delta): %d ms, Dirección: %s",
            92  		f.Name, f.State, f.LocalTime, f.DateFollower, f.CommunicationTime,
            93  		f.TripTime, f.DiffTime, f.Delta, f.Address)
            94  }
            95  
        

        View as plain text

        src/goberkeley/berkeley/follower_state.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/follower_state.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  // FollowerState representa los posibles estados de un seguidor durante el proceso de actualización de la hora del sistema.
             4  type FollowerState string
             5  
             6  const (
             7  	// RESPONDED indica que el seguidor ha respondido correctamente a la solicitud del líder.
             8  	Responded FollowerState = "RESPONDED"
             9  
            10  	// NO_RESPONSE indica que el seguidor no ha respondido a la solicitud dentro del tiempo esperado.
            11  	NoResponse FollowerState = "NO_RESPONSE"
            12  
            13  	// CONNECTION_ERROR indica que hubo un error de conexión al intentar comunicarse con el seguidor.
            14  	ConnectionError FollowerState = "CONNECTION_ERROR"
            15  
            16  	// REQUEST_NOT_SENT indica que la solicitud de actualización de la hora no fue enviada debido a algún error.
            17  	RequestNotSent FollowerState = "REQUEST_NOT_SENT"
            18  
            19  	// REQUEST_DELTA_SENT indica que la solicitud de actualización de la hora fue enviada al seguidor para actualizar su hora.
            20  	RequestDeltaSent FollowerState = "REQUEST_DELTA_SENT"
            21  
            22  	// TIME_ERROR_SENT_UPDATE indica que la solicitud de actualización de la hora fue enviada pero hubo un error en ese envío.
            23  	TimeErrorSentUpdate FollowerState = "TIME_ERROR_SENT_UPDATE"
            24  
            25  	// TIME_UPDATED indica que la hora del sistema del seguidor se actualizó correctamente.
            26  	TimeUpdated FollowerState = "TIME_UPDATED"
            27  
            28  	// ERROR_CLOSE indica que  no pude enviar el cierre del socket en el seguidor.
            29  	ErrorClose FollowerState = "ERROR_CLOSE"
            30  
            31  	// Ok_CLOSE indica que   pude  cerrar el socket en el seguidor.
            32  	OkClose FollowerState = "Ok_CLOSE"
            33  )
            34  
        

        View as plain text

        src/goberkeley/berkeley/anode.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/anode.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"errors"
             5  	"log"
             6  	"time"
             7  
             8  	zmq "github.com/pebbe/zmq4" // Librería para trabajar con ZeroMQ
             9  )
            10  
            11  // Interfaz Handler con el método HandleProcess
            12  type Handler interface {
            13  	HandleProcess(message string) (string, error)
            14  }
            15  
            16  // AbstractNode proporciona la funcionalidad base para nodos en el sistema.
            17  type AbstractNode struct {
            18  	Name          string
            19  	Address       string
            20  	Timeout       time.Duration
            21  	NodeAddresses map[string]string
            22  	Context       *zmq.Context
            23  	Socket        *zmq.Socket
            24  	Logger        *log.Logger
            25  	Handler       // Composición de la interfaz Handler
            26  }
            27  
            28  // NewAbstractNode crea e inicializa un nuevo nodo base.
            29  func NewAbstractNode(name, address string, timeout time.Duration) (*AbstractNode, error) {
            30  	context, err := zmq.NewContext()
            31  	if err != nil {
            32  		return nil, errors.New("error al crear el contexto ZeroMQ")
            33  	}
            34  
            35  	return &AbstractNode{
            36  		Name:    name,
            37  		Address: address,
            38  		Timeout: timeout,
            39  		Context: context,
            40  		Logger:  log.Default(),
            41  	}, nil
            42  }
            43  
            44  // InitializeNodeWithAddresses inicializa un nodo con direcciones de otros nodos.
            45  func InitializeNodeWithAddresses(name, address string, timeout time.Duration, addresses map[string]string) (*AbstractNode, error) {
            46  	var n *AbstractNode
            47  	n, err := NewAbstractNode(name, address, timeout)
            48  	if err != nil {
            49  		return nil, err
            50  	}
            51  	n.NodeAddresses = addresses
            52  	n.Logger.Printf("Nodo %s inicializado con direcciones %v", n.Name, addresses)
            53  	return n, nil
            54  }
            55  
            56  // SendMessageSync envía un mensaje de forma síncrona y espera una respuesta.
            57  func (n *AbstractNode) SendMessageSync(address string, message string) (string, error) {
            58  	// Creación del socket REQ (Request) para enviar el mensaje
            59  	var socket *zmq.Socket
            60  	socket, err := n.Context.NewSocket(zmq.REQ)
            61  	if err != nil {
            62  		n.Logger.Printf("Error al crear el socket REQ: %v", err) // Traza adicional
            63  		return "", errors.New("error al crear el socket REQ")
            64  	}
            65  	defer socket.Close()
            66  
            67  	// Establecer el timeout para recibir respuestas
            68  	socket.SetRcvtimeo(n.Timeout * time.Millisecond) // Convertir el timeout a milisegundos
            69  
            70  	// Traza: Mostrar el valor del timeout configurado
            71  	n.Logger.Printf("Timeout de recepción configurado a: %v milisegundos", int64(n.Timeout)) // Traza para el timeout
            72  
            73  	// Conectar al socket en la dirección proporcionada
            74  	err = socket.Connect("tcp://" + address)
            75  	if err != nil {
            76  		n.Logger.Printf("Error al conectar con %s: %v", address, err) // Traza adicional
            77  		return "", errors.New("error al conectar con " + address)
            78  	}
            79  
            80  	n.Logger.Printf("Conectado a %s", address) // Traza para verificar la conexión
            81  
            82  	// Enviar el mensaje al servidor
            83  	_, err = socket.Send(message, 0)
            84  	if err != nil {
            85  		n.Logger.Printf("Error al enviar el mensaje a %s: %v", address, err) // Traza adicional
            86  		return "", errors.New("error al enviar el mensaje")
            87  	}
            88  
            89  	n.Logger.Printf("Mensaje enviado a %s: %s", address, message) // Traza de envío
            90  
            91  	// Intentar recibir la respuesta
            92  	reply, err := socket.Recv(0)
            93  	if err != nil {
            94  		n.Logger.Printf("Error al recibir respuesta de %s: %v", address, err) // Traza para el error de recepción
            95  		return "", errors.New("no se recibió respuesta del socket")
            96  	}
            97  
            98  	n.Logger.Printf("Respuesta recibida de %s: %s", address, reply) // Traza de respuesta recibida
            99  	return reply, nil
           100  }
           101  
           102  // SendMessageAsync envía un mensaje de manera asíncrona.
           103  func (n *AbstractNode) SendMessageAsync(address, message string) error {
           104  	socket, err := n.Context.NewSocket(zmq.PUSH)
           105  	if err != nil {
           106  		return errors.New("error al crear el socket PUSH")
           107  	}
           108  	defer socket.Close()
           109  
           110  	err = socket.Connect("tcp://" + address)
           111  	if err != nil {
           112  		return errors.New("error al conectar con " + address)
           113  	}
           114  
           115  	_, err = socket.Send(message, 0)
           116  	if err != nil {
           117  		return errors.New("error al enviar el mensaje")
           118  	}
           119  
           120  	n.Logger.Printf("Mensaje asincrónico enviado a %s: %s", address, message)
           121  	return nil
           122  }
           123  
           124  // StartListening inicia el proceso de escucha para mensajes entrantes en el nodo.
           125  // Configura un socket de tipo REP (Response) para recibir y responder a mensajes.
           126  func (n *AbstractNode) StartListening() error {
           127  	// Log para indicar que estamos intentando crear un socket REP.
           128  	n.Logger.Printf("Intentando crear un socket REP para el nodo %s en la dirección %s", n.Name, n.Address)
           129  	socket, err := n.Context.NewSocket(zmq.REP)
           130  	if err != nil {
           131  		// Si ocurre un error al crear el socket, loguea el error y retorna un mensaje de error.
           132  		n.Logger.Printf("Error al crear el socket REP: %v", err)
           133  		return errors.New("error al crear el socket REP")
           134  	}
           135  	n.Socket = socket
           136  	n.Logger.Printf("Socket REP creado exitosamente para el nodo %s", n.Name)
           137  
           138  	// Enlaza el socket a la dirección TCP proporcionada en el nodo para esperar conexiones.
           139  	n.Logger.Printf("Enlazando el socket REP en la dirección tcp://%s", n.Address)
           140  	err = socket.Bind("tcp://" + n.Address)
           141  	if err != nil {
           142  		// Si ocurre un error al enlazar el socket, loguea el error y retorna un mensaje de error.
           143  		n.Logger.Printf("Error al enlazar el socket en %s: %v", n.Address, err)
           144  		return errors.New("error al enlazar el socket en " + n.Address)
           145  	}
           146  	n.Logger.Printf("Socket enlazado exitosamente en %s", n.Address)
           147  
           148  	// Inicia una nueva goroutine para escuchar de manera concurrente sin bloquear el hilo principal.
           149  	n.Logger.Printf("Iniciando goroutine para escuchar en el nodo %s", n.Name)
           150  	go func() {
           151  		// Logea que el nodo ha comenzado a escuchar en la dirección configurada.
           152  		n.Logger.Printf("Nodo %s escuchando en %s", n.Name, n.Address)
           153  
           154  		// Entra en un bucle infinito para recibir y procesar mensajes.
           155  		for {
           156  			// Recibe un mensaje del socket.
           157  			n.Logger.Printf("Esperando mensaje en %s...", n.Name)
           158  			message, err := socket.Recv(0)
           159  			if err != nil {
           160  				// Si ocurre un error al recibir el mensaje, loguea el error y termina el bucle.
           161  				n.Logger.Printf("Error al recibir mensaje: %v", err)
           162  				break
           163  			}
           164  			n.Logger.Printf("Mensaje recibido en %s: %v", n.Name, message)
           165  
           166  			// Llama al método HandleProcess, que es implementado por el tipo real de nodo (Follower, Leader, etc.).
           167  			// Este método procesará el mensaje recibido y generará una respuesta.
           168  			n.Logger.Printf("Procesando mensaje en %s...", n.Name)
           169  			response, err := n.Handler.HandleProcess(message)
           170  			if err != nil {
           171  				// Si hay un error al procesar el mensaje, loguea el error y termina el bucle.
           172  				n.Logger.Printf("Error en HandleProcess en %s: %v", n.Name, err)
           173  				break
           174  			}
           175  
           176  			// Envía la respuesta de vuelta al cliente a través del socket.
           177  			n.Logger.Printf("Enviando respuesta en %s: %v", n.Name, response)
           178  			_, err = socket.Send(response, 0)
           179  			if err != nil {
           180  				// Si ocurre un error al enviar la respuesta, loguea el error y termina el bucle.
           181  				n.Logger.Printf("Error al enviar respuesta en %s: %v", n.Name, err)
           182  				break
           183  			}
           184  		}
           185  	}()
           186  
           187  	// La función regresa nil si todo se configura correctamente y la goroutine se inicia sin errores.
           188  	n.Logger.Printf("Escucha iniciada exitosamente en el nodo %s", n.Name)
           189  	return nil
           190  }
           191  
           192  // Close cierra los recursos del nodo.
           193  func (n *AbstractNode) Close() error {
           194  	if n.Socket != nil {
           195  		n.Socket.Close()
           196  		n.Logger.Printf("Socket cerrado para el nodo %s", n.Name)
           197  	}
           198  	if n.Context != nil {
           199  		n.Context.Term()
           200  		n.Logger.Printf("Contexto cerrado para el nodo %s", n.Name)
           201  	}
           202  	return nil
           203  }
           204  
           205  // handleProcess debe ser sobrescrito por las subclases para procesar mensajes.
           206  func (n *AbstractNode) handleProcess(message string) string {
           207  	n.Logger.Printf("Procesando mensaje: %s", message)
           208  	return `{"status":"unhandled"}`
           209  }
           210  
        

        View as plain text

        src/goberkeley/berkeley/inode.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/inode.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"time"
             5  )
             6  
             7  // INode define las operaciones básicas para un nodo en el sistema.
             8  type INode interface {
             9  	InitializeNode(name string, address string, timeout time.Duration) error
            10  	InitializeNodeWithAddresses(name string, address string, timeout time.Duration, addresses map[string]string) error
            11  	SendMessageSync(address string, message string) (string, error)
            12  	SendMessageAsync(address string, message string) error
            13  	StartListening() error
            14  	StartAlgorithm() error
            15  	Close() error
            16  }
            17  
        

        View as plain text

        src/goberkeley/berkeley/leader.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/leader.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  
             7  	"log"
             8  	"strconv"
             9  	"sync"
            10  	"time"
            11  )
            12  
            13  // Mensaje JSON que se envía al seguidor.
            14  type TimeRequest struct {
            15  	Message    string `json:"message"`
            16  	Operation  string `json:"operation"`
            17  	Time       int64  `json:"time"`
            18  	LeaderAddr string `json:"leader_address"`
            19  }
            20  type DeltaRequest struct {
            21  	Message    string `json:"message"`
            22  	Operation  string `json:"operation"`
            23  	Delta      int64  `json:"delta"`
            24  	LeaderAddr string `json:"leader_address"`
            25  }
            26  type closeRequest struct {
            27  	Message    string `json:"message"`
            28  	Operation  string `json:"operation"`
            29  	LeaderAddr string `json:"leader_address"`
            30  }
            31  
            32  // Leader representa el nodo líder en el sistema Berkeley.
            33  type Leader struct {
            34  	aAbstractNode          *AbstractNode
            35  	UnreachableFollowers   map[string]*FollowerInfo
            36  	SuccessfulFollowers    map[string]*FollowerInfo
            37  	NonRespondingFollowers map[string]*FollowerInfo
            38  	TimeUpdatedFollowers   map[string]*FollowerInfo
            39  	FailedFollowers        map[string]*FollowerInfo
            40  	//mu                     sync.Mutex // Mutex para proteger los mapas en accesos concurrentes
            41  	Logger *log.Logger
            42  }
            43  
            44  // HandleProcess implements Handler.
            45  func (l *Leader) HandleProcess(message string) (string, error) {
            46  	panic("unimplemented")
            47  }
            48  
            49  // InitializeLeaderNode crea e inicializa un nuevo nodo líder.
            50  func InitializeLeaderNode(name, address string, timeout time.Duration, nodeAddresses map[string]string) (*Leader, error) {
            51  	// Suponiendo que InitializeNodeWithAddresses crea un nodo base y devuelve un puntero a AbstractNode
            52  	baseNode, err := InitializeNodeWithAddresses(name, address, timeout, nodeAddresses)
            53  	if err != nil {
            54  		return nil, err
            55  	}
            56  
            57  	// Inicializamos el líder, asignando el nodo base y un logger
            58  	leader := &Leader{
            59  		aAbstractNode: baseNode, // Asignamos el puntero a AbstractNode
            60  		Logger:        log.Default(),
            61  	}
            62  	leader.aAbstractNode.Handler = leader
            63  
            64  	return leader, nil
            65  }
            66  func (l *Leader) initStructs() {
            67  	if l.UnreachableFollowers == nil {
            68  		l.UnreachableFollowers = make(map[string]*FollowerInfo)
            69  	}
            70  	if l.SuccessfulFollowers == nil {
            71  		l.SuccessfulFollowers = make(map[string]*FollowerInfo)
            72  	}
            73  	if l.NonRespondingFollowers == nil {
            74  		l.NonRespondingFollowers = make(map[string]*FollowerInfo)
            75  	}
            76  	if l.TimeUpdatedFollowers == nil {
            77  		l.TimeUpdatedFollowers = make(map[string]*FollowerInfo)
            78  	}
            79  	if l.FailedFollowers == nil {
            80  		l.FailedFollowers = make(map[string]*FollowerInfo)
            81  	}
            82  }
            83  
            84  // StartAlgorithm implementa el algoritmo de sincronización Berkeley para el líder.
            85  func (l *Leader) StartAlgorithm() {
            86  	l.Logger.Println("Iniciando algoritmo de sincronización Berkeley...")
            87  	l.initStructs()
            88  	// Simula el envío de solicitudes de tiempo a los seguidores
            89  	l.processFollowers()
            90  
            91  	// Fase 2: Calcular el delta con la media de los tiempos
            92  	log.Println("** Fase 2 **: Calcular el delta con la media de los tiempos")
            93  	delta := l.calculateDeltaTimeDifference()
            94  	if delta != 0 {
            95  		// Paso 3: Actualizar relojes de los seguidores
            96  		log.Println("** Paso 3 **: Llamar a los seguidores para actualizar sus relojes")
            97  		l.callFollowersWithUpdatedTime(delta)
            98  
            99  		// Fase 4: Enviar mensaje de cierre
           100  		log.Println("** Fase 4 **: Enviar mensaje de cierre a los seguidores")
           101  		l.sendCloseMessagesToFollowers()
           102  
           103  		// Fase 5: Mostrar los resultados finales
           104  		log.Println("** Fase 5: Mostrar los resultados de la sincronización")
           105  		l.printResults()
           106  	} else {
           107  		// Se registra esta situación para comprobarlo más adelante en los logs
           108  		log.Println("El resultado del delta es cero por lo que no se envían actualizaciones a ningún seguidor.")
           109  	}
           110  }
           111  func (l *Leader) processFollowers() {
           112  	leaderTime := time.Now().UnixMilli() // T0
           113  	leaderAddr := l.aAbstractNode.Address
           114  
           115  	log.Printf("processFollowers: leaderAddr %s leaderTime %d.", leaderAddr, leaderTime)
           116  
           117  	// Lista de seguidores
           118  	followers := l.aAbstractNode.NodeAddresses
           119  
           120  	// Canal para los resultados
           121  	results := make(chan *FollowerInfo, len(followers))
           122  	var wg sync.WaitGroup
           123  
           124  	// Enviar solicitudes a los seguidores concurrentemente
           125  	for followerName, followerAddr := range followers {
           126  		wg.Add(1)
           127  		go func(name, addr string) {
           128  			defer wg.Done()
           129  			log.Printf("Enviando solicitud de tiempo a %s (%s).", name, addr)
           130  			l.sendTimeRequestToFollower(name, addr, leaderTime, leaderAddr, results)
           131  		}(followerName, followerAddr)
           132  	}
           133  
           134  	// Cerrar el canal una vez que todos los goroutines hayan terminado
           135  	go func() {
           136  		wg.Wait()
           137  		close(results)
           138  	}()
           139  
           140  	// Recoger y procesar los resultados
           141  	for res := range results {
           142  		if res.GetState() == "RESPONDED" {
           143  			// Seguidor que respondió correctamente
           144  			l.SuccessfulFollowers[res.GetName()] = res
           145  			log.Printf("Seguidor %s respondió correctamente con tiempo local: %d ms", res.GetName(), res.GetLocalTime())
           146  		} else if res.GetState() == "TIMEOUT" {
           147  			// Seguidor que no respondió a tiempo
           148  			l.NonRespondingFollowers[res.GetName()] = res
           149  			log.Printf("Seguidor %s no respondió a tiempo.", res.GetName())
           150  		} else {
           151  			// Seguidor que tuvo algún otro problema
           152  			l.FailedFollowers[res.GetName()] = res
           153  			log.Printf("Seguidor %s falló con estado: %s.", res.GetName(), res.GetState())
           154  		}
           155  	}
           156  
           157  	// Log final para indicar que el procesamiento de seguidores ha terminado
           158  	log.Printf("Proceso de seguidores completado. Respuestas procesadas: %d, Fallos: %d.", len(l.SuccessfulFollowers), len(l.NonRespondingFollowers))
           159  }
           160  func (l *Leader) sendTimeRequestToFollower(followerName, followerAddr string, leaderTime int64, leaderAddr string, results chan<- *FollowerInfo) {
           161  	// Crear el mensaje JSON
           162  	request := TimeRequest{
           163  		Message:    "Requesting time sync",
           164  		Operation:  "GET_TIME",
           165  		Time:       leaderTime, //T0
           166  		LeaderAddr: leaderAddr,
           167  	}
           168  
           169  	// Serializar el mensaje en formato JSON
           170  	requestData, err := json.Marshal(request)
           171  	if err != nil {
           172  		log.Printf("Error al serializar la solicitud a JSON: %v", err)
           173  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           174  		return
           175  	}
           176  
           177  	// Convertir el JSON a string
           178  	requestString := string(requestData)
           179  	log.Printf("Solicitud enviada a %s: %s", followerAddr, requestString)
           180  
           181  	// Enviar el mensaje al seguidor y recibir la respuesta
           182  	reply, err := l.aAbstractNode.SendMessageSync(followerAddr, requestString)
           183  	if err != nil {
           184  		log.Printf("Error al recibir respuesta de %s: %v", followerAddr, err)
           185  		followError := NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           186  		results <- followError
           187  		return
           188  	}
           189  
           190  	log.Printf("Respuesta recibida de %s: %s", followerAddr, reply)
           191  
           192  	// Deserializar la respuesta JSON
           193  	var response map[string]string
           194  	if err := json.Unmarshal([]byte(reply), &response); err != nil {
           195  		log.Printf("Error al procesar la respuesta de %s: %v", followerAddr, err)
           196  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           197  		return
           198  	}
           199  
           200  	// Calcular la diferencia de tiempo
           201  	endCommTime := time.Now().UnixMilli() // T0
           202  	timeComm := endCommTime - leaderTime
           203  	log.Printf("Tiempo de comunicación: %d ms", timeComm)
           204  
           205  	// Obtener el tiempo local del seguidor
           206  	localTimeStr, ok := response["localTime"]
           207  	if !ok {
           208  		log.Printf("No se encontró el campo 'localTime' en la respuesta de %s", followerAddr)
           209  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           210  		return
           211  	}
           212  
           213  	// Convertir el valor de localTime de string a int64
           214  	localTimeInt64, err := strconv.ParseInt(localTimeStr, 10, 64)
           215  	if err != nil {
           216  		log.Printf("Error al convertir 'localTime' a int64 de %s: %v", followerAddr, err)
           217  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           218  		return
           219  	}
           220  
           221  	// Enviar los resultados al canal
           222  	log.Printf("Tiempo local recibido de %s: %d", followerAddr, localTimeInt64)
           223  	foll := NewFollowerInfo(followerAddr, followerName, localTimeInt64, timeComm, 0)
           224  	foll.SetState(Responded)
           225  	results <- foll
           226  }
           227  
           228  // calculateDeltaTimeDifference calcula la diferencia de tiempo (delta) entre el tiempo local y los tiempos de los seguidores válidos.
           229  func (l *Leader) calculateDeltaTimeDifference() int64 {
           230  	// Log de inicio de la operación de cálculo de la diferencia de tiempo
           231  	log.Println("Calculando la diferencia de tiempo (delta)")
           232  
           233  	// Obtener el tiempo actual del líder
           234  	now := time.Now().UnixMilli()
           235  	var sumTime int64 = 0           // Suma de los tiempos ajustados de los seguidores
           236  	var validFollowersCount int = 0 // Contador de seguidores con respuestas válidas
           237  
           238  	// Recorrer los seguidores exitosos y calcular la diferencia de tiempo para cada uno
           239  	for _, follower := range l.SuccessfulFollowers {
           240  		if follower.DiffTime != int64(^uint64(0)>>1) { // Verificar si el seguidor tiene un tiempo válido (Long.MAX_VALUE en Java)
           241  			followerTime := now + follower.DiffTime // Calcular el tiempo ajustado del seguidor
           242  			sumTime += followerTime                 // Sumar el tiempo ajustado
           243  			validFollowersCount++                   // Incrementar el contador de seguidores válidos
           244  		}
           245  	}
           246  
           247  	// Si se tienen seguidores válidos, calcular la diferencia de tiempo promedio
           248  	if validFollowersCount > 0 {
           249  		newNow := sumTime / int64(validFollowersCount) // Calcular el promedio de los tiempos de los seguidores
           250  		delta := newNow - now                          // Calcular la diferencia de tiempo (delta)
           251  
           252  		// Log de los resultados calculados
           253  		log.Printf("Nuevo tiempo calculado (new_now): %d\n", newNow)
           254  		log.Printf("Diferencia global (δ): %d\n", delta)
           255  
           256  		// Retornar la diferencia de tiempo (delta)
           257  		return delta
           258  	} else {
           259  		// Si no hay seguidores válidos, registrar advertencia y retornar 0
           260  		log.Println("No se han recibido respuestas válidas de los seguidores.")
           261  		return 0
           262  	}
           263  }
           264  
           265  func (l *Leader) callFollowersWithUpdatedTime(delta int64) error {
           266  	log.Printf("Enviando actualización de tiempo a los seguidores con delta: %d", delta)
           267  
           268  	// Crear un canal para gestionar las tareas concurrentes
           269  	ch := make(chan *FollowerInfo, len(l.SuccessfulFollowers))
           270  
           271  	// Usamos un WaitGroup para esperar que todas las goroutines terminen
           272  	var wg sync.WaitGroup
           273  
           274  	// Enviar las tareas en paralelo para cada seguidor
           275  	for _, follower := range l.SuccessfulFollowers {
           276  		wg.Add(1) // Incrementamos el contador del WaitGroup
           277  		go func(follower FollowerInfo) {
           278  			defer wg.Done() // Decrementamos el contador del WaitGroup cuando la goroutine termina
           279  			followerInfo := l.sendTimeUpdateToFollower(follower, delta)
           280  			ch <- followerInfo
           281  		}(*follower)
           282  	}
           283  
           284  	// Iniciar una goroutine para cerrar el canal una vez que todas las goroutines hayan terminado
           285  	go func() {
           286  		wg.Wait() // Esperamos a que todas las goroutines terminen
           287  		close(ch) // Cerramos el canal después de que todas las goroutines hayan enviado sus respuestas
           288  	}()
           289  
           290  	// Procesar las respuestas conforme vayan llegando
           291  	for followerInfo := range ch {
           292  		if followerInfo.State == "TIME_UPDATED" {
           293  			log.Printf("El seguidor %s respondió correctamente al cambio del timer.", followerInfo.Name)
           294  			l.TimeUpdatedFollowers[followerInfo.Name] = followerInfo
           295  		} else {
           296  			log.Printf("El seguidor %s no respondió al cambio de su timer.", followerInfo.Name)
           297  			l.FailedFollowers[followerInfo.Name] = followerInfo
           298  		}
           299  	}
           300  
           301  	return nil
           302  }
           303  
           304  func (l *Leader) sendTimeUpdateToFollower(follower FollowerInfo, delta int64) *FollowerInfo {
           305  
           306  	// Crear el mapa con la solicitud
           307  	request := DeltaRequest{
           308  		Message:    "Modifica el tiempo del sistema de tu servidor con el diferencial.",
           309  		Operation:  "UPDATE_TIME",
           310  		Delta:      delta,
           311  		LeaderAddr: l.aAbstractNode.Address,
           312  	}
           313  
           314  	// Serializar la solicitud a JSON
           315  	jsonRequest, err := json.Marshal(request)
           316  	if err != nil {
           317  		log.Printf("Error al serializar la solicitud para el seguidor %s: %v", follower.Name, err)
           318  		follower.State = TimeErrorSentUpdate
           319  		return &follower
           320  	}
           321  
           322  	requestString := string(jsonRequest)
           323  	log.Printf("Solicitud enviada a %s: %s", follower.GetAddress(), requestString)
           324  	// Enviar la solicitud
           325  	reply, err := l.aAbstractNode.SendMessageSync(follower.GetAddress(), requestString)
           326  	if err != nil {
           327  		log.Printf("Error al recibir respuesta de %s: %v", follower.GetAddress(), err)
           328  		followError := NewFollowerInfo(follower.GetAddress(), follower.GetName(), 0, 0, 0)
           329  		followError.State = TimeErrorSentUpdate
           330  		return followError
           331  	}
           332  
           333  	var response map[string]string
           334  	err = json.Unmarshal([]byte(reply), &response)
           335  	if err != nil {
           336  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", follower.Name, err)
           337  		follower.State = TimeErrorSentUpdate
           338  		return &follower
           339  	}
           340  
           341  	// Registrar la respuesta
           342  	followerName := response["followerName"]
           343  	operation := response["operation"]
           344  	log.Printf("Respuesta de %s: Operación %s exitosa", followerName, operation)
           345  
           346  	follower.State = TimeUpdated
           347  	return &follower
           348  }
           349  func (l *Leader) sendCloseMessagesToFollowers() {
           350  	// Crear un WaitGroup para esperar a que todas las goroutines terminen
           351  	var wg sync.WaitGroup
           352  
           353  	// Canal para recibir los resultados de las goroutines
           354  	resultCh := make(chan string, len(l.TimeUpdatedFollowers))
           355  
           356  	// Enviar mensaje de cierre a cada seguidor de manera concurrente
           357  	for _, follower := range l.TimeUpdatedFollowers {
           358  		wg.Add(1)
           359  		go func(follower FollowerInfo) {
           360  			defer wg.Done()
           361  
           362  			// Enviar el mensaje de cierre
           363  			err := l.sendCloseMessage(follower.Address, follower.Name)
           364  			if err != nil {
           365  				resultCh <- fmt.Sprintf("Error al enviar mensaje de cierre a %s: %s", follower.Name, err)
           366  				return
           367  			}
           368  
           369  			// Simulamos que el mensaje fue enviado exitosamente
           370  			resultCh <- fmt.Sprintf("Mensaje de cierre enviado con éxito a %s", follower.Name)
           371  		}(*follower)
           372  	}
           373  
           374  	// Esperar a que todas las goroutines terminen
           375  	go func() {
           376  		wg.Wait()
           377  		close(resultCh)
           378  	}()
           379  
           380  	// Procesar los resultados a medida que vayan llegando
           381  	for result := range resultCh {
           382  		log.Println(result)
           383  	}
           384  
           385  }
           386  
           387  // SendCloseMessage envía un mensaje de cierre a un seguidor.
           388  // Simulación de la función para enviar mensaje de cierre a un seguidor
           389  func (l *Leader) sendCloseMessage(followerAddress, followerName string) *FollowerInfo {
           390  	log.Printf("Enviando mensaje de cierre a %s...", followerAddress)
           391  
           392  	request := closeRequest{
           393  		Message:    "Cerrar conexión",
           394  		Operation:  "CLOSE",
           395  		LeaderAddr: l.aAbstractNode.Address,
           396  	}
           397  
           398  	// Convertir el mensaje a JSON
           399  	jsonRequest, err := json.Marshal(request)
           400  	if err != nil {
           401  		log.Printf("error al crear mensaje de cierre: %w", err)
           402  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           403  		followError.State = ErrorClose
           404  		return followError
           405  	}
           406  
           407  	// Simulamos el envío del mensaje al seguidor (usando un canal)
           408  	log.Printf("Mensaje de cierre enviado a %s: %s", followerAddress, jsonRequest)
           409  	// Serializar la solicitud a JSON
           410  
           411  	requestString := string(jsonRequest)
           412  	log.Printf("Solicitud enviada a %s: %s", followerAddress, requestString)
           413  	// Enviar la solicitud
           414  	reply, err := l.aAbstractNode.SendMessageSync(followerAddress, requestString)
           415  	if err != nil {
           416  		log.Printf("Error al recibir respuesta de %s: %v", followerAddress, err)
           417  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           418  		followError.State = ErrorClose
           419  		return followError
           420  	}
           421  
           422  	var response map[string]string
           423  	err = json.Unmarshal([]byte(reply), &response)
           424  	if err != nil {
           425  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", followerName, err)
           426  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           427  		followError.State = ErrorClose
           428  		return followError
           429  	}
           430  	// Simulamos una respuesta (en un caso real recibirías la respuesta desde el socket)
           431  	// Aquí se simula un éxito.
           432  	response = map[string]string{
           433  		"followerName": followerAddress,
           434  		"operation":    "CLOSE",
           435  	}
           436  
           437  	// Convertimos la respuesta a JSON
           438  	jsonResponse, err := json.Marshal(response)
           439  	if err != nil {
           440  		log.Printf("error al procesar la respuesta: %w", err)
           441  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           442  		followError.State = ErrorClose
           443  		return followError
           444  	}
           445  
           446  	// Simulamos la recepción de la respuesta (en un caso real, recibirías el mensaje desde el socket)
           447  	log.Printf("Respuesta recibida de %s: %s", followerAddress, jsonResponse)
           448  	follow := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           449  	follow.State = OkClose
           450  	return follow
           451  }
           452  
           453  // PrintResults muestra los resultados del algoritmo.
           454  func (l *Leader) printResults() {
           455  	l.Logger.Println("Resultados del algoritmo Berkeley:")
           456  
           457  	// Mostrar seguidores inalcanzables
           458  	l.Logger.Println("Seguidores inalcanzables:")
           459  	for key, value := range l.UnreachableFollowers {
           460  		l.Logger.Printf("- %s: %v", key, value)
           461  	}
           462  
           463  	// Mostrar seguidores que no respondieron a tiempo
           464  	l.Logger.Println("Seguidores que no respondieron a tiempo:")
           465  	for key, value := range l.NonRespondingFollowers {
           466  		l.Logger.Printf("- %s: %v", key, value)
           467  	}
           468  
           469  	// Mostrar seguidores que respondieron correctamente
           470  	l.Logger.Println("Seguidores que respondieron correctamente:")
           471  	for key, value := range l.SuccessfulFollowers {
           472  		l.Logger.Printf("- %s: %v", key, value)
           473  	}
           474  
           475  	// Mostrar seguidores que actualizaron su tiempo correctamente
           476  	l.Logger.Println("Seguidores que actualizaron su tiempo correctamente:")
           477  	for key, value := range l.TimeUpdatedFollowers {
           478  		l.Logger.Printf("- %s: %v", key, value)
           479  	}
           480  
           481  	// Mostrar seguidores que no pudieron actualizar su tiempo
           482  	l.Logger.Println("Seguidores que no pudieron actualizar su tiempo:")
           483  	for key, value := range l.FailedFollowers {
           484  		l.Logger.Printf("- %s: %v", key, value)
           485  	}
           486  }
           487  func (l *Leader) Close() {
           488  	l.aAbstractNode.Close()
           489  }
           490  
        

        View as plain text

        src/goberkeley/berkeley/leader.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/leader.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  
             7  	"log"
             8  	"strconv"
             9  	"sync"
            10  	"time"
            11  )
            12  
            13  // Mensaje JSON que se envía al seguidor.
            14  type TimeRequest struct {
            15  	Message    string `json:"message"`
            16  	Operation  string `json:"operation"`
            17  	Time       int64  `json:"time"`
            18  	LeaderAddr string `json:"leader_address"`
            19  }
            20  type DeltaRequest struct {
            21  	Message    string `json:"message"`
            22  	Operation  string `json:"operation"`
            23  	Delta      int64  `json:"delta"`
            24  	LeaderAddr string `json:"leader_address"`
            25  }
            26  type closeRequest struct {
            27  	Message    string `json:"message"`
            28  	Operation  string `json:"operation"`
            29  	LeaderAddr string `json:"leader_address"`
            30  }
            31  
            32  // Leader representa el nodo líder en el sistema Berkeley.
            33  type Leader struct {
            34  	aAbstractNode          *AbstractNode
            35  	UnreachableFollowers   map[string]*FollowerInfo
            36  	SuccessfulFollowers    map[string]*FollowerInfo
            37  	NonRespondingFollowers map[string]*FollowerInfo
            38  	TimeUpdatedFollowers   map[string]*FollowerInfo
            39  	FailedFollowers        map[string]*FollowerInfo
            40  	//mu                     sync.Mutex // Mutex para proteger los mapas en accesos concurrentes
            41  	Logger *log.Logger
            42  }
            43  
            44  // HandleProcess implements Handler.
            45  func (l *Leader) HandleProcess(message string) (string, error) {
            46  	panic("unimplemented")
            47  }
            48  
            49  // InitializeLeaderNode crea e inicializa un nuevo nodo líder.
            50  func InitializeLeaderNode(name, address string, timeout time.Duration, nodeAddresses map[string]string) (*Leader, error) {
            51  	// Suponiendo que InitializeNodeWithAddresses crea un nodo base y devuelve un puntero a AbstractNode
            52  	baseNode, err := InitializeNodeWithAddresses(name, address, timeout, nodeAddresses)
            53  	if err != nil {
            54  		return nil, err
            55  	}
            56  
            57  	// Inicializamos el líder, asignando el nodo base y un logger
            58  	leader := &Leader{
            59  		aAbstractNode: baseNode, // Asignamos el puntero a AbstractNode
            60  		Logger:        log.Default(),
            61  	}
            62  	leader.aAbstractNode.Handler = leader
            63  
            64  	return leader, nil
            65  }
            66  func (l *Leader) initStructs() {
            67  	if l.UnreachableFollowers == nil {
            68  		l.UnreachableFollowers = make(map[string]*FollowerInfo)
            69  	}
            70  	if l.SuccessfulFollowers == nil {
            71  		l.SuccessfulFollowers = make(map[string]*FollowerInfo)
            72  	}
            73  	if l.NonRespondingFollowers == nil {
            74  		l.NonRespondingFollowers = make(map[string]*FollowerInfo)
            75  	}
            76  	if l.TimeUpdatedFollowers == nil {
            77  		l.TimeUpdatedFollowers = make(map[string]*FollowerInfo)
            78  	}
            79  	if l.FailedFollowers == nil {
            80  		l.FailedFollowers = make(map[string]*FollowerInfo)
            81  	}
            82  }
            83  
            84  // StartAlgorithm implementa el algoritmo de sincronización Berkeley para el líder.
            85  func (l *Leader) StartAlgorithm() {
            86  	l.Logger.Println("Iniciando algoritmo de sincronización Berkeley...")
            87  	l.initStructs()
            88  	// Simula el envío de solicitudes de tiempo a los seguidores
            89  	l.processFollowers()
            90  
            91  	// Fase 2: Calcular el delta con la media de los tiempos
            92  	log.Println("** Fase 2 **: Calcular el delta con la media de los tiempos")
            93  	delta := l.calculateDeltaTimeDifference()
            94  	if delta != 0 {
            95  		// Paso 3: Actualizar relojes de los seguidores
            96  		log.Println("** Paso 3 **: Llamar a los seguidores para actualizar sus relojes")
            97  		l.callFollowersWithUpdatedTime(delta)
            98  
            99  		// Fase 4: Enviar mensaje de cierre
           100  		log.Println("** Fase 4 **: Enviar mensaje de cierre a los seguidores")
           101  		l.sendCloseMessagesToFollowers()
           102  
           103  		// Fase 5: Mostrar los resultados finales
           104  		log.Println("** Fase 5: Mostrar los resultados de la sincronización")
           105  		l.printResults()
           106  	} else {
           107  		// Se registra esta situación para comprobarlo más adelante en los logs
           108  		log.Println("El resultado del delta es cero por lo que no se envían actualizaciones a ningún seguidor.")
           109  	}
           110  }
           111  func (l *Leader) processFollowers() {
           112  	leaderTime := time.Now().UnixMilli() // T0
           113  	leaderAddr := l.aAbstractNode.Address
           114  
           115  	log.Printf("processFollowers: leaderAddr %s leaderTime %d.", leaderAddr, leaderTime)
           116  
           117  	// Lista de seguidores
           118  	followers := l.aAbstractNode.NodeAddresses
           119  
           120  	// Canal para los resultados
           121  	results := make(chan *FollowerInfo, len(followers))
           122  	var wg sync.WaitGroup
           123  
           124  	// Enviar solicitudes a los seguidores concurrentemente
           125  	for followerName, followerAddr := range followers {
           126  		wg.Add(1)
           127  		go func(name, addr string) {
           128  			defer wg.Done()
           129  			log.Printf("Enviando solicitud de tiempo a %s (%s).", name, addr)
           130  			l.sendTimeRequestToFollower(name, addr, leaderTime, leaderAddr, results)
           131  		}(followerName, followerAddr)
           132  	}
           133  
           134  	// Cerrar el canal una vez que todos los goroutines hayan terminado
           135  	go func() {
           136  		wg.Wait()
           137  		close(results)
           138  	}()
           139  
           140  	// Recoger y procesar los resultados
           141  	for res := range results {
           142  		if res.GetState() == "RESPONDED" {
           143  			// Seguidor que respondió correctamente
           144  			l.SuccessfulFollowers[res.GetName()] = res
           145  			log.Printf("Seguidor %s respondió correctamente con tiempo local: %d ms", res.GetName(), res.GetLocalTime())
           146  		} else if res.GetState() == "TIMEOUT" {
           147  			// Seguidor que no respondió a tiempo
           148  			l.NonRespondingFollowers[res.GetName()] = res
           149  			log.Printf("Seguidor %s no respondió a tiempo.", res.GetName())
           150  		} else {
           151  			// Seguidor que tuvo algún otro problema
           152  			l.FailedFollowers[res.GetName()] = res
           153  			log.Printf("Seguidor %s falló con estado: %s.", res.GetName(), res.GetState())
           154  		}
           155  	}
           156  
           157  	// Log final para indicar que el procesamiento de seguidores ha terminado
           158  	log.Printf("Proceso de seguidores completado. Respuestas procesadas: %d, Fallos: %d.", len(l.SuccessfulFollowers), len(l.NonRespondingFollowers))
           159  }
           160  func (l *Leader) sendTimeRequestToFollower(followerName, followerAddr string, leaderTime int64, leaderAddr string, results chan<- *FollowerInfo) {
           161  	// Crear el mensaje JSON
           162  	request := TimeRequest{
           163  		Message:    "Requesting time sync",
           164  		Operation:  "GET_TIME",
           165  		Time:       leaderTime, //T0
           166  		LeaderAddr: leaderAddr,
           167  	}
           168  
           169  	// Serializar el mensaje en formato JSON
           170  	requestData, err := json.Marshal(request)
           171  	if err != nil {
           172  		log.Printf("Error al serializar la solicitud a JSON: %v", err)
           173  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           174  		return
           175  	}
           176  
           177  	// Convertir el JSON a string
           178  	requestString := string(requestData)
           179  	log.Printf("Solicitud enviada a %s: %s", followerAddr, requestString)
           180  
           181  	// Enviar el mensaje al seguidor y recibir la respuesta
           182  	reply, err := l.aAbstractNode.SendMessageSync(followerAddr, requestString)
           183  	if err != nil {
           184  		log.Printf("Error al recibir respuesta de %s: %v", followerAddr, err)
           185  		followError := NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           186  		results <- followError
           187  		return
           188  	}
           189  
           190  	log.Printf("Respuesta recibida de %s: %s", followerAddr, reply)
           191  
           192  	// Deserializar la respuesta JSON
           193  	var response map[string]string
           194  	if err := json.Unmarshal([]byte(reply), &response); err != nil {
           195  		log.Printf("Error al procesar la respuesta de %s: %v", followerAddr, err)
           196  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           197  		return
           198  	}
           199  
           200  	// Calcular la diferencia de tiempo
           201  	endCommTime := time.Now().UnixMilli() // T0
           202  	timeComm := endCommTime - leaderTime
           203  	log.Printf("Tiempo de comunicación: %d ms", timeComm)
           204  
           205  	// Obtener el tiempo local del seguidor
           206  	localTimeStr, ok := response["localTime"]
           207  	if !ok {
           208  		log.Printf("No se encontró el campo 'localTime' en la respuesta de %s", followerAddr)
           209  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           210  		return
           211  	}
           212  
           213  	// Convertir el valor de localTime de string a int64
           214  	localTimeInt64, err := strconv.ParseInt(localTimeStr, 10, 64)
           215  	if err != nil {
           216  		log.Printf("Error al convertir 'localTime' a int64 de %s: %v", followerAddr, err)
           217  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           218  		return
           219  	}
           220  
           221  	// Enviar los resultados al canal
           222  	log.Printf("Tiempo local recibido de %s: %d", followerAddr, localTimeInt64)
           223  	foll := NewFollowerInfo(followerAddr, followerName, localTimeInt64, timeComm, 0)
           224  	foll.SetState(Responded)
           225  	results <- foll
           226  }
           227  
           228  // calculateDeltaTimeDifference calcula la diferencia de tiempo (delta) entre el tiempo local y los tiempos de los seguidores válidos.
           229  func (l *Leader) calculateDeltaTimeDifference() int64 {
           230  	// Log de inicio de la operación de cálculo de la diferencia de tiempo
           231  	log.Println("Calculando la diferencia de tiempo (delta)")
           232  
           233  	// Obtener el tiempo actual del líder
           234  	now := time.Now().UnixMilli()
           235  	var sumTime int64 = 0           // Suma de los tiempos ajustados de los seguidores
           236  	var validFollowersCount int = 0 // Contador de seguidores con respuestas válidas
           237  
           238  	// Recorrer los seguidores exitosos y calcular la diferencia de tiempo para cada uno
           239  	for _, follower := range l.SuccessfulFollowers {
           240  		if follower.DiffTime != int64(^uint64(0)>>1) { // Verificar si el seguidor tiene un tiempo válido (Long.MAX_VALUE en Java)
           241  			followerTime := now + follower.DiffTime // Calcular el tiempo ajustado del seguidor
           242  			sumTime += followerTime                 // Sumar el tiempo ajustado
           243  			validFollowersCount++                   // Incrementar el contador de seguidores válidos
           244  		}
           245  	}
           246  
           247  	// Si se tienen seguidores válidos, calcular la diferencia de tiempo promedio
           248  	if validFollowersCount > 0 {
           249  		newNow := sumTime / int64(validFollowersCount) // Calcular el promedio de los tiempos de los seguidores
           250  		delta := newNow - now                          // Calcular la diferencia de tiempo (delta)
           251  
           252  		// Log de los resultados calculados
           253  		log.Printf("Nuevo tiempo calculado (new_now): %d\n", newNow)
           254  		log.Printf("Diferencia global (δ): %d\n", delta)
           255  
           256  		// Retornar la diferencia de tiempo (delta)
           257  		return delta
           258  	} else {
           259  		// Si no hay seguidores válidos, registrar advertencia y retornar 0
           260  		log.Println("No se han recibido respuestas válidas de los seguidores.")
           261  		return 0
           262  	}
           263  }
           264  
           265  func (l *Leader) callFollowersWithUpdatedTime(delta int64) error {
           266  	log.Printf("Enviando actualización de tiempo a los seguidores con delta: %d", delta)
           267  
           268  	// Crear un canal para gestionar las tareas concurrentes
           269  	ch := make(chan *FollowerInfo, len(l.SuccessfulFollowers))
           270  
           271  	// Usamos un WaitGroup para esperar que todas las goroutines terminen
           272  	var wg sync.WaitGroup
           273  
           274  	// Enviar las tareas en paralelo para cada seguidor
           275  	for _, follower := range l.SuccessfulFollowers {
           276  		wg.Add(1) // Incrementamos el contador del WaitGroup
           277  		go func(follower FollowerInfo) {
           278  			defer wg.Done() // Decrementamos el contador del WaitGroup cuando la goroutine termina
           279  			followerInfo := l.sendTimeUpdateToFollower(follower, delta)
           280  			ch <- followerInfo
           281  		}(*follower)
           282  	}
           283  
           284  	// Iniciar una goroutine para cerrar el canal una vez que todas las goroutines hayan terminado
           285  	go func() {
           286  		wg.Wait() // Esperamos a que todas las goroutines terminen
           287  		close(ch) // Cerramos el canal después de que todas las goroutines hayan enviado sus respuestas
           288  	}()
           289  
           290  	// Procesar las respuestas conforme vayan llegando
           291  	for followerInfo := range ch {
           292  		if followerInfo.State == "TIME_UPDATED" {
           293  			log.Printf("El seguidor %s respondió correctamente al cambio del timer.", followerInfo.Name)
           294  			l.TimeUpdatedFollowers[followerInfo.Name] = followerInfo
           295  		} else {
           296  			log.Printf("El seguidor %s no respondió al cambio de su timer.", followerInfo.Name)
           297  			l.FailedFollowers[followerInfo.Name] = followerInfo
           298  		}
           299  	}
           300  
           301  	return nil
           302  }
           303  
           304  func (l *Leader) sendTimeUpdateToFollower(follower FollowerInfo, delta int64) *FollowerInfo {
           305  
           306  	// Crear el mapa con la solicitud
           307  	request := DeltaRequest{
           308  		Message:    "Modifica el tiempo del sistema de tu servidor con el diferencial.",
           309  		Operation:  "UPDATE_TIME",
           310  		Delta:      delta,
           311  		LeaderAddr: l.aAbstractNode.Address,
           312  	}
           313  
           314  	// Serializar la solicitud a JSON
           315  	jsonRequest, err := json.Marshal(request)
           316  	if err != nil {
           317  		log.Printf("Error al serializar la solicitud para el seguidor %s: %v", follower.Name, err)
           318  		follower.State = TimeErrorSentUpdate
           319  		return &follower
           320  	}
           321  
           322  	requestString := string(jsonRequest)
           323  	log.Printf("Solicitud enviada a %s: %s", follower.GetAddress(), requestString)
           324  	// Enviar la solicitud
           325  	reply, err := l.aAbstractNode.SendMessageSync(follower.GetAddress(), requestString)
           326  	if err != nil {
           327  		log.Printf("Error al recibir respuesta de %s: %v", follower.GetAddress(), err)
           328  		followError := NewFollowerInfo(follower.GetAddress(), follower.GetName(), 0, 0, 0)
           329  		followError.State = TimeErrorSentUpdate
           330  		return followError
           331  	}
           332  
           333  	var response map[string]string
           334  	err = json.Unmarshal([]byte(reply), &response)
           335  	if err != nil {
           336  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", follower.Name, err)
           337  		follower.State = TimeErrorSentUpdate
           338  		return &follower
           339  	}
           340  
           341  	// Registrar la respuesta
           342  	followerName := response["followerName"]
           343  	operation := response["operation"]
           344  	log.Printf("Respuesta de %s: Operación %s exitosa", followerName, operation)
           345  
           346  	follower.State = TimeUpdated
           347  	return &follower
           348  }
           349  func (l *Leader) sendCloseMessagesToFollowers() {
           350  	// Crear un WaitGroup para esperar a que todas las goroutines terminen
           351  	var wg sync.WaitGroup
           352  
           353  	// Canal para recibir los resultados de las goroutines
           354  	resultCh := make(chan string, len(l.TimeUpdatedFollowers))
           355  
           356  	// Enviar mensaje de cierre a cada seguidor de manera concurrente
           357  	for _, follower := range l.TimeUpdatedFollowers {
           358  		wg.Add(1)
           359  		go func(follower FollowerInfo) {
           360  			defer wg.Done()
           361  
           362  			// Enviar el mensaje de cierre
           363  			err := l.sendCloseMessage(follower.Address, follower.Name)
           364  			if err != nil {
           365  				resultCh <- fmt.Sprintf("Error al enviar mensaje de cierre a %s: %s", follower.Name, err)
           366  				return
           367  			}
           368  
           369  			// Simulamos que el mensaje fue enviado exitosamente
           370  			resultCh <- fmt.Sprintf("Mensaje de cierre enviado con éxito a %s", follower.Name)
           371  		}(*follower)
           372  	}
           373  
           374  	// Esperar a que todas las goroutines terminen
           375  	go func() {
           376  		wg.Wait()
           377  		close(resultCh)
           378  	}()
           379  
           380  	// Procesar los resultados a medida que vayan llegando
           381  	for result := range resultCh {
           382  		log.Println(result)
           383  	}
           384  
           385  }
           386  
           387  // SendCloseMessage envía un mensaje de cierre a un seguidor.
           388  // Simulación de la función para enviar mensaje de cierre a un seguidor
           389  func (l *Leader) sendCloseMessage(followerAddress, followerName string) *FollowerInfo {
           390  	log.Printf("Enviando mensaje de cierre a %s...", followerAddress)
           391  
           392  	request := closeRequest{
           393  		Message:    "Cerrar conexión",
           394  		Operation:  "CLOSE",
           395  		LeaderAddr: l.aAbstractNode.Address,
           396  	}
           397  
           398  	// Convertir el mensaje a JSON
           399  	jsonRequest, err := json.Marshal(request)
           400  	if err != nil {
           401  		log.Printf("error al crear mensaje de cierre: %w", err)
           402  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           403  		followError.State = ErrorClose
           404  		return followError
           405  	}
           406  
           407  	// Simulamos el envío del mensaje al seguidor (usando un canal)
           408  	log.Printf("Mensaje de cierre enviado a %s: %s", followerAddress, jsonRequest)
           409  	// Serializar la solicitud a JSON
           410  
           411  	requestString := string(jsonRequest)
           412  	log.Printf("Solicitud enviada a %s: %s", followerAddress, requestString)
           413  	// Enviar la solicitud
           414  	reply, err := l.aAbstractNode.SendMessageSync(followerAddress, requestString)
           415  	if err != nil {
           416  		log.Printf("Error al recibir respuesta de %s: %v", followerAddress, err)
           417  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           418  		followError.State = ErrorClose
           419  		return followError
           420  	}
           421  
           422  	var response map[string]string
           423  	err = json.Unmarshal([]byte(reply), &response)
           424  	if err != nil {
           425  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", followerName, err)
           426  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           427  		followError.State = ErrorClose
           428  		return followError
           429  	}
           430  	// Simulamos una respuesta (en un caso real recibirías la respuesta desde el socket)
           431  	// Aquí se simula un éxito.
           432  	response = map[string]string{
           433  		"followerName": followerAddress,
           434  		"operation":    "CLOSE",
           435  	}
           436  
           437  	// Convertimos la respuesta a JSON
           438  	jsonResponse, err := json.Marshal(response)
           439  	if err != nil {
           440  		log.Printf("error al procesar la respuesta: %w", err)
           441  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           442  		followError.State = ErrorClose
           443  		return followError
           444  	}
           445  
           446  	// Simulamos la recepción de la respuesta (en un caso real, recibirías el mensaje desde el socket)
           447  	log.Printf("Respuesta recibida de %s: %s", followerAddress, jsonResponse)
           448  	follow := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           449  	follow.State = OkClose
           450  	return follow
           451  }
           452  
           453  // PrintResults muestra los resultados del algoritmo.
           454  func (l *Leader) printResults() {
           455  	l.Logger.Println("Resultados del algoritmo Berkeley:")
           456  
           457  	// Mostrar seguidores inalcanzables
           458  	l.Logger.Println("Seguidores inalcanzables:")
           459  	for key, value := range l.UnreachableFollowers {
           460  		l.Logger.Printf("- %s: %v", key, value)
           461  	}
           462  
           463  	// Mostrar seguidores que no respondieron a tiempo
           464  	l.Logger.Println("Seguidores que no respondieron a tiempo:")
           465  	for key, value := range l.NonRespondingFollowers {
           466  		l.Logger.Printf("- %s: %v", key, value)
           467  	}
           468  
           469  	// Mostrar seguidores que respondieron correctamente
           470  	l.Logger.Println("Seguidores que respondieron correctamente:")
           471  	for key, value := range l.SuccessfulFollowers {
           472  		l.Logger.Printf("- %s: %v", key, value)
           473  	}
           474  
           475  	// Mostrar seguidores que actualizaron su tiempo correctamente
           476  	l.Logger.Println("Seguidores que actualizaron su tiempo correctamente:")
           477  	for key, value := range l.TimeUpdatedFollowers {
           478  		l.Logger.Printf("- %s: %v", key, value)
           479  	}
           480  
           481  	// Mostrar seguidores que no pudieron actualizar su tiempo
           482  	l.Logger.Println("Seguidores que no pudieron actualizar su tiempo:")
           483  	for key, value := range l.FailedFollowers {
           484  		l.Logger.Printf("- %s: %v", key, value)
           485  	}
           486  }
           487  func (l *Leader) Close() {
           488  	l.aAbstractNode.Close()
           489  }
           490  
        

        View as plain text

        src/goberkeley/berkeley/leader.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/leader.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  
             7  	"log"
             8  	"strconv"
             9  	"sync"
            10  	"time"
            11  )
            12  
            13  // Mensaje JSON que se envía al seguidor.
            14  type TimeRequest struct {
            15  	Message    string `json:"message"`
            16  	Operation  string `json:"operation"`
            17  	Time       int64  `json:"time"`
            18  	LeaderAddr string `json:"leader_address"`
            19  }
            20  type DeltaRequest struct {
            21  	Message    string `json:"message"`
            22  	Operation  string `json:"operation"`
            23  	Delta      int64  `json:"delta"`
            24  	LeaderAddr string `json:"leader_address"`
            25  }
            26  type closeRequest struct {
            27  	Message    string `json:"message"`
            28  	Operation  string `json:"operation"`
            29  	LeaderAddr string `json:"leader_address"`
            30  }
            31  
            32  // Leader representa el nodo líder en el sistema Berkeley.
            33  type Leader struct {
            34  	aAbstractNode          *AbstractNode
            35  	UnreachableFollowers   map[string]*FollowerInfo
            36  	SuccessfulFollowers    map[string]*FollowerInfo
            37  	NonRespondingFollowers map[string]*FollowerInfo
            38  	TimeUpdatedFollowers   map[string]*FollowerInfo
            39  	FailedFollowers        map[string]*FollowerInfo
            40  	//mu                     sync.Mutex // Mutex para proteger los mapas en accesos concurrentes
            41  	Logger *log.Logger
            42  }
            43  
            44  // HandleProcess implements Handler.
            45  func (l *Leader) HandleProcess(message string) (string, error) {
            46  	panic("unimplemented")
            47  }
            48  
            49  // InitializeLeaderNode crea e inicializa un nuevo nodo líder.
            50  func InitializeLeaderNode(name, address string, timeout time.Duration, nodeAddresses map[string]string) (*Leader, error) {
            51  	// Suponiendo que InitializeNodeWithAddresses crea un nodo base y devuelve un puntero a AbstractNode
            52  	baseNode, err := InitializeNodeWithAddresses(name, address, timeout, nodeAddresses)
            53  	if err != nil {
            54  		return nil, err
            55  	}
            56  
            57  	// Inicializamos el líder, asignando el nodo base y un logger
            58  	leader := &Leader{
            59  		aAbstractNode: baseNode, // Asignamos el puntero a AbstractNode
            60  		Logger:        log.Default(),
            61  	}
            62  	leader.aAbstractNode.Handler = leader
            63  
            64  	return leader, nil
            65  }
            66  func (l *Leader) initStructs() {
            67  	if l.UnreachableFollowers == nil {
            68  		l.UnreachableFollowers = make(map[string]*FollowerInfo)
            69  	}
            70  	if l.SuccessfulFollowers == nil {
            71  		l.SuccessfulFollowers = make(map[string]*FollowerInfo)
            72  	}
            73  	if l.NonRespondingFollowers == nil {
            74  		l.NonRespondingFollowers = make(map[string]*FollowerInfo)
            75  	}
            76  	if l.TimeUpdatedFollowers == nil {
            77  		l.TimeUpdatedFollowers = make(map[string]*FollowerInfo)
            78  	}
            79  	if l.FailedFollowers == nil {
            80  		l.FailedFollowers = make(map[string]*FollowerInfo)
            81  	}
            82  }
            83  
            84  // StartAlgorithm implementa el algoritmo de sincronización Berkeley para el líder.
            85  func (l *Leader) StartAlgorithm() {
            86  	l.Logger.Println("Iniciando algoritmo de sincronización Berkeley...")
            87  	l.initStructs()
            88  	// Simula el envío de solicitudes de tiempo a los seguidores
            89  	l.processFollowers()
            90  
            91  	// Fase 2: Calcular el delta con la media de los tiempos
            92  	log.Println("** Fase 2 **: Calcular el delta con la media de los tiempos")
            93  	delta := l.calculateDeltaTimeDifference()
            94  	if delta != 0 {
            95  		// Paso 3: Actualizar relojes de los seguidores
            96  		log.Println("** Paso 3 **: Llamar a los seguidores para actualizar sus relojes")
            97  		l.callFollowersWithUpdatedTime(delta)
            98  
            99  		// Fase 4: Enviar mensaje de cierre
           100  		log.Println("** Fase 4 **: Enviar mensaje de cierre a los seguidores")
           101  		l.sendCloseMessagesToFollowers()
           102  
           103  		// Fase 5: Mostrar los resultados finales
           104  		log.Println("** Fase 5: Mostrar los resultados de la sincronización")
           105  		l.printResults()
           106  	} else {
           107  		// Se registra esta situación para comprobarlo más adelante en los logs
           108  		log.Println("El resultado del delta es cero por lo que no se envían actualizaciones a ningún seguidor.")
           109  	}
           110  }
           111  func (l *Leader) processFollowers() {
           112  	leaderTime := time.Now().UnixMilli() // T0
           113  	leaderAddr := l.aAbstractNode.Address
           114  
           115  	log.Printf("processFollowers: leaderAddr %s leaderTime %d.", leaderAddr, leaderTime)
           116  
           117  	// Lista de seguidores
           118  	followers := l.aAbstractNode.NodeAddresses
           119  
           120  	// Canal para los resultados
           121  	results := make(chan *FollowerInfo, len(followers))
           122  	var wg sync.WaitGroup
           123  
           124  	// Enviar solicitudes a los seguidores concurrentemente
           125  	for followerName, followerAddr := range followers {
           126  		wg.Add(1)
           127  		go func(name, addr string) {
           128  			defer wg.Done()
           129  			log.Printf("Enviando solicitud de tiempo a %s (%s).", name, addr)
           130  			l.sendTimeRequestToFollower(name, addr, leaderTime, leaderAddr, results)
           131  		}(followerName, followerAddr)
           132  	}
           133  
           134  	// Cerrar el canal una vez que todos los goroutines hayan terminado
           135  	go func() {
           136  		wg.Wait()
           137  		close(results)
           138  	}()
           139  
           140  	// Recoger y procesar los resultados
           141  	for res := range results {
           142  		if res.GetState() == "RESPONDED" {
           143  			// Seguidor que respondió correctamente
           144  			l.SuccessfulFollowers[res.GetName()] = res
           145  			log.Printf("Seguidor %s respondió correctamente con tiempo local: %d ms", res.GetName(), res.GetLocalTime())
           146  		} else if res.GetState() == "TIMEOUT" {
           147  			// Seguidor que no respondió a tiempo
           148  			l.NonRespondingFollowers[res.GetName()] = res
           149  			log.Printf("Seguidor %s no respondió a tiempo.", res.GetName())
           150  		} else {
           151  			// Seguidor que tuvo algún otro problema
           152  			l.FailedFollowers[res.GetName()] = res
           153  			log.Printf("Seguidor %s falló con estado: %s.", res.GetName(), res.GetState())
           154  		}
           155  	}
           156  
           157  	// Log final para indicar que el procesamiento de seguidores ha terminado
           158  	log.Printf("Proceso de seguidores completado. Respuestas procesadas: %d, Fallos: %d.", len(l.SuccessfulFollowers), len(l.NonRespondingFollowers))
           159  }
           160  func (l *Leader) sendTimeRequestToFollower(followerName, followerAddr string, leaderTime int64, leaderAddr string, results chan<- *FollowerInfo) {
           161  	// Crear el mensaje JSON
           162  	request := TimeRequest{
           163  		Message:    "Requesting time sync",
           164  		Operation:  "GET_TIME",
           165  		Time:       leaderTime, //T0
           166  		LeaderAddr: leaderAddr,
           167  	}
           168  
           169  	// Serializar el mensaje en formato JSON
           170  	requestData, err := json.Marshal(request)
           171  	if err != nil {
           172  		log.Printf("Error al serializar la solicitud a JSON: %v", err)
           173  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           174  		return
           175  	}
           176  
           177  	// Convertir el JSON a string
           178  	requestString := string(requestData)
           179  	log.Printf("Solicitud enviada a %s: %s", followerAddr, requestString)
           180  
           181  	// Enviar el mensaje al seguidor y recibir la respuesta
           182  	reply, err := l.aAbstractNode.SendMessageSync(followerAddr, requestString)
           183  	if err != nil {
           184  		log.Printf("Error al recibir respuesta de %s: %v", followerAddr, err)
           185  		followError := NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           186  		results <- followError
           187  		return
           188  	}
           189  
           190  	log.Printf("Respuesta recibida de %s: %s", followerAddr, reply)
           191  
           192  	// Deserializar la respuesta JSON
           193  	var response map[string]string
           194  	if err := json.Unmarshal([]byte(reply), &response); err != nil {
           195  		log.Printf("Error al procesar la respuesta de %s: %v", followerAddr, err)
           196  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           197  		return
           198  	}
           199  
           200  	// Calcular la diferencia de tiempo
           201  	endCommTime := time.Now().UnixMilli() // T0
           202  	timeComm := endCommTime - leaderTime
           203  	log.Printf("Tiempo de comunicación: %d ms", timeComm)
           204  
           205  	// Obtener el tiempo local del seguidor
           206  	localTimeStr, ok := response["localTime"]
           207  	if !ok {
           208  		log.Printf("No se encontró el campo 'localTime' en la respuesta de %s", followerAddr)
           209  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           210  		return
           211  	}
           212  
           213  	// Convertir el valor de localTime de string a int64
           214  	localTimeInt64, err := strconv.ParseInt(localTimeStr, 10, 64)
           215  	if err != nil {
           216  		log.Printf("Error al convertir 'localTime' a int64 de %s: %v", followerAddr, err)
           217  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           218  		return
           219  	}
           220  
           221  	// Enviar los resultados al canal
           222  	log.Printf("Tiempo local recibido de %s: %d", followerAddr, localTimeInt64)
           223  	foll := NewFollowerInfo(followerAddr, followerName, localTimeInt64, timeComm, 0)
           224  	foll.SetState(Responded)
           225  	results <- foll
           226  }
           227  
           228  // calculateDeltaTimeDifference calcula la diferencia de tiempo (delta) entre el tiempo local y los tiempos de los seguidores válidos.
           229  func (l *Leader) calculateDeltaTimeDifference() int64 {
           230  	// Log de inicio de la operación de cálculo de la diferencia de tiempo
           231  	log.Println("Calculando la diferencia de tiempo (delta)")
           232  
           233  	// Obtener el tiempo actual del líder
           234  	now := time.Now().UnixMilli()
           235  	var sumTime int64 = 0           // Suma de los tiempos ajustados de los seguidores
           236  	var validFollowersCount int = 0 // Contador de seguidores con respuestas válidas
           237  
           238  	// Recorrer los seguidores exitosos y calcular la diferencia de tiempo para cada uno
           239  	for _, follower := range l.SuccessfulFollowers {
           240  		if follower.DiffTime != int64(^uint64(0)>>1) { // Verificar si el seguidor tiene un tiempo válido (Long.MAX_VALUE en Java)
           241  			followerTime := now + follower.DiffTime // Calcular el tiempo ajustado del seguidor
           242  			sumTime += followerTime                 // Sumar el tiempo ajustado
           243  			validFollowersCount++                   // Incrementar el contador de seguidores válidos
           244  		}
           245  	}
           246  
           247  	// Si se tienen seguidores válidos, calcular la diferencia de tiempo promedio
           248  	if validFollowersCount > 0 {
           249  		newNow := sumTime / int64(validFollowersCount) // Calcular el promedio de los tiempos de los seguidores
           250  		delta := newNow - now                          // Calcular la diferencia de tiempo (delta)
           251  
           252  		// Log de los resultados calculados
           253  		log.Printf("Nuevo tiempo calculado (new_now): %d\n", newNow)
           254  		log.Printf("Diferencia global (δ): %d\n", delta)
           255  
           256  		// Retornar la diferencia de tiempo (delta)
           257  		return delta
           258  	} else {
           259  		// Si no hay seguidores válidos, registrar advertencia y retornar 0
           260  		log.Println("No se han recibido respuestas válidas de los seguidores.")
           261  		return 0
           262  	}
           263  }
           264  
           265  func (l *Leader) callFollowersWithUpdatedTime(delta int64) error {
           266  	log.Printf("Enviando actualización de tiempo a los seguidores con delta: %d", delta)
           267  
           268  	// Crear un canal para gestionar las tareas concurrentes
           269  	ch := make(chan *FollowerInfo, len(l.SuccessfulFollowers))
           270  
           271  	// Usamos un WaitGroup para esperar que todas las goroutines terminen
           272  	var wg sync.WaitGroup
           273  
           274  	// Enviar las tareas en paralelo para cada seguidor
           275  	for _, follower := range l.SuccessfulFollowers {
           276  		wg.Add(1) // Incrementamos el contador del WaitGroup
           277  		go func(follower FollowerInfo) {
           278  			defer wg.Done() // Decrementamos el contador del WaitGroup cuando la goroutine termina
           279  			followerInfo := l.sendTimeUpdateToFollower(follower, delta)
           280  			ch <- followerInfo
           281  		}(*follower)
           282  	}
           283  
           284  	// Iniciar una goroutine para cerrar el canal una vez que todas las goroutines hayan terminado
           285  	go func() {
           286  		wg.Wait() // Esperamos a que todas las goroutines terminen
           287  		close(ch) // Cerramos el canal después de que todas las goroutines hayan enviado sus respuestas
           288  	}()
           289  
           290  	// Procesar las respuestas conforme vayan llegando
           291  	for followerInfo := range ch {
           292  		if followerInfo.State == "TIME_UPDATED" {
           293  			log.Printf("El seguidor %s respondió correctamente al cambio del timer.", followerInfo.Name)
           294  			l.TimeUpdatedFollowers[followerInfo.Name] = followerInfo
           295  		} else {
           296  			log.Printf("El seguidor %s no respondió al cambio de su timer.", followerInfo.Name)
           297  			l.FailedFollowers[followerInfo.Name] = followerInfo
           298  		}
           299  	}
           300  
           301  	return nil
           302  }
           303  
           304  func (l *Leader) sendTimeUpdateToFollower(follower FollowerInfo, delta int64) *FollowerInfo {
           305  
           306  	// Crear el mapa con la solicitud
           307  	request := DeltaRequest{
           308  		Message:    "Modifica el tiempo del sistema de tu servidor con el diferencial.",
           309  		Operation:  "UPDATE_TIME",
           310  		Delta:      delta,
           311  		LeaderAddr: l.aAbstractNode.Address,
           312  	}
           313  
           314  	// Serializar la solicitud a JSON
           315  	jsonRequest, err := json.Marshal(request)
           316  	if err != nil {
           317  		log.Printf("Error al serializar la solicitud para el seguidor %s: %v", follower.Name, err)
           318  		follower.State = TimeErrorSentUpdate
           319  		return &follower
           320  	}
           321  
           322  	requestString := string(jsonRequest)
           323  	log.Printf("Solicitud enviada a %s: %s", follower.GetAddress(), requestString)
           324  	// Enviar la solicitud
           325  	reply, err := l.aAbstractNode.SendMessageSync(follower.GetAddress(), requestString)
           326  	if err != nil {
           327  		log.Printf("Error al recibir respuesta de %s: %v", follower.GetAddress(), err)
           328  		followError := NewFollowerInfo(follower.GetAddress(), follower.GetName(), 0, 0, 0)
           329  		followError.State = TimeErrorSentUpdate
           330  		return followError
           331  	}
           332  
           333  	var response map[string]string
           334  	err = json.Unmarshal([]byte(reply), &response)
           335  	if err != nil {
           336  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", follower.Name, err)
           337  		follower.State = TimeErrorSentUpdate
           338  		return &follower
           339  	}
           340  
           341  	// Registrar la respuesta
           342  	followerName := response["followerName"]
           343  	operation := response["operation"]
           344  	log.Printf("Respuesta de %s: Operación %s exitosa", followerName, operation)
           345  
           346  	follower.State = TimeUpdated
           347  	return &follower
           348  }
           349  func (l *Leader) sendCloseMessagesToFollowers() {
           350  	// Crear un WaitGroup para esperar a que todas las goroutines terminen
           351  	var wg sync.WaitGroup
           352  
           353  	// Canal para recibir los resultados de las goroutines
           354  	resultCh := make(chan string, len(l.TimeUpdatedFollowers))
           355  
           356  	// Enviar mensaje de cierre a cada seguidor de manera concurrente
           357  	for _, follower := range l.TimeUpdatedFollowers {
           358  		wg.Add(1)
           359  		go func(follower FollowerInfo) {
           360  			defer wg.Done()
           361  
           362  			// Enviar el mensaje de cierre
           363  			err := l.sendCloseMessage(follower.Address, follower.Name)
           364  			if err != nil {
           365  				resultCh <- fmt.Sprintf("Error al enviar mensaje de cierre a %s: %s", follower.Name, err)
           366  				return
           367  			}
           368  
           369  			// Simulamos que el mensaje fue enviado exitosamente
           370  			resultCh <- fmt.Sprintf("Mensaje de cierre enviado con éxito a %s", follower.Name)
           371  		}(*follower)
           372  	}
           373  
           374  	// Esperar a que todas las goroutines terminen
           375  	go func() {
           376  		wg.Wait()
           377  		close(resultCh)
           378  	}()
           379  
           380  	// Procesar los resultados a medida que vayan llegando
           381  	for result := range resultCh {
           382  		log.Println(result)
           383  	}
           384  
           385  }
           386  
           387  // SendCloseMessage envía un mensaje de cierre a un seguidor.
           388  // Simulación de la función para enviar mensaje de cierre a un seguidor
           389  func (l *Leader) sendCloseMessage(followerAddress, followerName string) *FollowerInfo {
           390  	log.Printf("Enviando mensaje de cierre a %s...", followerAddress)
           391  
           392  	request := closeRequest{
           393  		Message:    "Cerrar conexión",
           394  		Operation:  "CLOSE",
           395  		LeaderAddr: l.aAbstractNode.Address,
           396  	}
           397  
           398  	// Convertir el mensaje a JSON
           399  	jsonRequest, err := json.Marshal(request)
           400  	if err != nil {
           401  		log.Printf("error al crear mensaje de cierre: %w", err)
           402  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           403  		followError.State = ErrorClose
           404  		return followError
           405  	}
           406  
           407  	// Simulamos el envío del mensaje al seguidor (usando un canal)
           408  	log.Printf("Mensaje de cierre enviado a %s: %s", followerAddress, jsonRequest)
           409  	// Serializar la solicitud a JSON
           410  
           411  	requestString := string(jsonRequest)
           412  	log.Printf("Solicitud enviada a %s: %s", followerAddress, requestString)
           413  	// Enviar la solicitud
           414  	reply, err := l.aAbstractNode.SendMessageSync(followerAddress, requestString)
           415  	if err != nil {
           416  		log.Printf("Error al recibir respuesta de %s: %v", followerAddress, err)
           417  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           418  		followError.State = ErrorClose
           419  		return followError
           420  	}
           421  
           422  	var response map[string]string
           423  	err = json.Unmarshal([]byte(reply), &response)
           424  	if err != nil {
           425  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", followerName, err)
           426  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           427  		followError.State = ErrorClose
           428  		return followError
           429  	}
           430  	// Simulamos una respuesta (en un caso real recibirías la respuesta desde el socket)
           431  	// Aquí se simula un éxito.
           432  	response = map[string]string{
           433  		"followerName": followerAddress,
           434  		"operation":    "CLOSE",
           435  	}
           436  
           437  	// Convertimos la respuesta a JSON
           438  	jsonResponse, err := json.Marshal(response)
           439  	if err != nil {
           440  		log.Printf("error al procesar la respuesta: %w", err)
           441  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           442  		followError.State = ErrorClose
           443  		return followError
           444  	}
           445  
           446  	// Simulamos la recepción de la respuesta (en un caso real, recibirías el mensaje desde el socket)
           447  	log.Printf("Respuesta recibida de %s: %s", followerAddress, jsonResponse)
           448  	follow := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           449  	follow.State = OkClose
           450  	return follow
           451  }
           452  
           453  // PrintResults muestra los resultados del algoritmo.
           454  func (l *Leader) printResults() {
           455  	l.Logger.Println("Resultados del algoritmo Berkeley:")
           456  
           457  	// Mostrar seguidores inalcanzables
           458  	l.Logger.Println("Seguidores inalcanzables:")
           459  	for key, value := range l.UnreachableFollowers {
           460  		l.Logger.Printf("- %s: %v", key, value)
           461  	}
           462  
           463  	// Mostrar seguidores que no respondieron a tiempo
           464  	l.Logger.Println("Seguidores que no respondieron a tiempo:")
           465  	for key, value := range l.NonRespondingFollowers {
           466  		l.Logger.Printf("- %s: %v", key, value)
           467  	}
           468  
           469  	// Mostrar seguidores que respondieron correctamente
           470  	l.Logger.Println("Seguidores que respondieron correctamente:")
           471  	for key, value := range l.SuccessfulFollowers {
           472  		l.Logger.Printf("- %s: %v", key, value)
           473  	}
           474  
           475  	// Mostrar seguidores que actualizaron su tiempo correctamente
           476  	l.Logger.Println("Seguidores que actualizaron su tiempo correctamente:")
           477  	for key, value := range l.TimeUpdatedFollowers {
           478  		l.Logger.Printf("- %s: %v", key, value)
           479  	}
           480  
           481  	// Mostrar seguidores que no pudieron actualizar su tiempo
           482  	l.Logger.Println("Seguidores que no pudieron actualizar su tiempo:")
           483  	for key, value := range l.FailedFollowers {
           484  		l.Logger.Printf("- %s: %v", key, value)
           485  	}
           486  }
           487  func (l *Leader) Close() {
           488  	l.aAbstractNode.Close()
           489  }
           490  
        

        View as plain text

        src/goberkeley/berkeley/leader.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/leader.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  
             7  	"log"
             8  	"strconv"
             9  	"sync"
            10  	"time"
            11  )
            12  
            13  // Mensaje JSON que se envía al seguidor.
            14  type TimeRequest struct {
            15  	Message    string `json:"message"`
            16  	Operation  string `json:"operation"`
            17  	Time       int64  `json:"time"`
            18  	LeaderAddr string `json:"leader_address"`
            19  }
            20  type DeltaRequest struct {
            21  	Message    string `json:"message"`
            22  	Operation  string `json:"operation"`
            23  	Delta      int64  `json:"delta"`
            24  	LeaderAddr string `json:"leader_address"`
            25  }
            26  type closeRequest struct {
            27  	Message    string `json:"message"`
            28  	Operation  string `json:"operation"`
            29  	LeaderAddr string `json:"leader_address"`
            30  }
            31  
            32  // Leader representa el nodo líder en el sistema Berkeley.
            33  type Leader struct {
            34  	aAbstractNode          *AbstractNode
            35  	UnreachableFollowers   map[string]*FollowerInfo
            36  	SuccessfulFollowers    map[string]*FollowerInfo
            37  	NonRespondingFollowers map[string]*FollowerInfo
            38  	TimeUpdatedFollowers   map[string]*FollowerInfo
            39  	FailedFollowers        map[string]*FollowerInfo
            40  	//mu                     sync.Mutex // Mutex para proteger los mapas en accesos concurrentes
            41  	Logger *log.Logger
            42  }
            43  
            44  // HandleProcess implements Handler.
            45  func (l *Leader) HandleProcess(message string) (string, error) {
            46  	panic("unimplemented")
            47  }
            48  
            49  // InitializeLeaderNode crea e inicializa un nuevo nodo líder.
            50  func InitializeLeaderNode(name, address string, timeout time.Duration, nodeAddresses map[string]string) (*Leader, error) {
            51  	// Suponiendo que InitializeNodeWithAddresses crea un nodo base y devuelve un puntero a AbstractNode
            52  	baseNode, err := InitializeNodeWithAddresses(name, address, timeout, nodeAddresses)
            53  	if err != nil {
            54  		return nil, err
            55  	}
            56  
            57  	// Inicializamos el líder, asignando el nodo base y un logger
            58  	leader := &Leader{
            59  		aAbstractNode: baseNode, // Asignamos el puntero a AbstractNode
            60  		Logger:        log.Default(),
            61  	}
            62  	leader.aAbstractNode.Handler = leader
            63  
            64  	return leader, nil
            65  }
            66  func (l *Leader) initStructs() {
            67  	if l.UnreachableFollowers == nil {
            68  		l.UnreachableFollowers = make(map[string]*FollowerInfo)
            69  	}
            70  	if l.SuccessfulFollowers == nil {
            71  		l.SuccessfulFollowers = make(map[string]*FollowerInfo)
            72  	}
            73  	if l.NonRespondingFollowers == nil {
            74  		l.NonRespondingFollowers = make(map[string]*FollowerInfo)
            75  	}
            76  	if l.TimeUpdatedFollowers == nil {
            77  		l.TimeUpdatedFollowers = make(map[string]*FollowerInfo)
            78  	}
            79  	if l.FailedFollowers == nil {
            80  		l.FailedFollowers = make(map[string]*FollowerInfo)
            81  	}
            82  }
            83  
            84  // StartAlgorithm implementa el algoritmo de sincronización Berkeley para el líder.
            85  func (l *Leader) StartAlgorithm() {
            86  	l.Logger.Println("Iniciando algoritmo de sincronización Berkeley...")
            87  	l.initStructs()
            88  	// Simula el envío de solicitudes de tiempo a los seguidores
            89  	l.processFollowers()
            90  
            91  	// Fase 2: Calcular el delta con la media de los tiempos
            92  	log.Println("** Fase 2 **: Calcular el delta con la media de los tiempos")
            93  	delta := l.calculateDeltaTimeDifference()
            94  	if delta != 0 {
            95  		// Paso 3: Actualizar relojes de los seguidores
            96  		log.Println("** Paso 3 **: Llamar a los seguidores para actualizar sus relojes")
            97  		l.callFollowersWithUpdatedTime(delta)
            98  
            99  		// Fase 4: Enviar mensaje de cierre
           100  		log.Println("** Fase 4 **: Enviar mensaje de cierre a los seguidores")
           101  		l.sendCloseMessagesToFollowers()
           102  
           103  		// Fase 5: Mostrar los resultados finales
           104  		log.Println("** Fase 5: Mostrar los resultados de la sincronización")
           105  		l.printResults()
           106  	} else {
           107  		// Se registra esta situación para comprobarlo más adelante en los logs
           108  		log.Println("El resultado del delta es cero por lo que no se envían actualizaciones a ningún seguidor.")
           109  	}
           110  }
           111  func (l *Leader) processFollowers() {
           112  	leaderTime := time.Now().UnixMilli() // T0
           113  	leaderAddr := l.aAbstractNode.Address
           114  
           115  	log.Printf("processFollowers: leaderAddr %s leaderTime %d.", leaderAddr, leaderTime)
           116  
           117  	// Lista de seguidores
           118  	followers := l.aAbstractNode.NodeAddresses
           119  
           120  	// Canal para los resultados
           121  	results := make(chan *FollowerInfo, len(followers))
           122  	var wg sync.WaitGroup
           123  
           124  	// Enviar solicitudes a los seguidores concurrentemente
           125  	for followerName, followerAddr := range followers {
           126  		wg.Add(1)
           127  		go func(name, addr string) {
           128  			defer wg.Done()
           129  			log.Printf("Enviando solicitud de tiempo a %s (%s).", name, addr)
           130  			l.sendTimeRequestToFollower(name, addr, leaderTime, leaderAddr, results)
           131  		}(followerName, followerAddr)
           132  	}
           133  
           134  	// Cerrar el canal una vez que todos los goroutines hayan terminado
           135  	go func() {
           136  		wg.Wait()
           137  		close(results)
           138  	}()
           139  
           140  	// Recoger y procesar los resultados
           141  	for res := range results {
           142  		if res.GetState() == "RESPONDED" {
           143  			// Seguidor que respondió correctamente
           144  			l.SuccessfulFollowers[res.GetName()] = res
           145  			log.Printf("Seguidor %s respondió correctamente con tiempo local: %d ms", res.GetName(), res.GetLocalTime())
           146  		} else if res.GetState() == "TIMEOUT" {
           147  			// Seguidor que no respondió a tiempo
           148  			l.NonRespondingFollowers[res.GetName()] = res
           149  			log.Printf("Seguidor %s no respondió a tiempo.", res.GetName())
           150  		} else {
           151  			// Seguidor que tuvo algún otro problema
           152  			l.FailedFollowers[res.GetName()] = res
           153  			log.Printf("Seguidor %s falló con estado: %s.", res.GetName(), res.GetState())
           154  		}
           155  	}
           156  
           157  	// Log final para indicar que el procesamiento de seguidores ha terminado
           158  	log.Printf("Proceso de seguidores completado. Respuestas procesadas: %d, Fallos: %d.", len(l.SuccessfulFollowers), len(l.NonRespondingFollowers))
           159  }
           160  func (l *Leader) sendTimeRequestToFollower(followerName, followerAddr string, leaderTime int64, leaderAddr string, results chan<- *FollowerInfo) {
           161  	// Crear el mensaje JSON
           162  	request := TimeRequest{
           163  		Message:    "Requesting time sync",
           164  		Operation:  "GET_TIME",
           165  		Time:       leaderTime, //T0
           166  		LeaderAddr: leaderAddr,
           167  	}
           168  
           169  	// Serializar el mensaje en formato JSON
           170  	requestData, err := json.Marshal(request)
           171  	if err != nil {
           172  		log.Printf("Error al serializar la solicitud a JSON: %v", err)
           173  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           174  		return
           175  	}
           176  
           177  	// Convertir el JSON a string
           178  	requestString := string(requestData)
           179  	log.Printf("Solicitud enviada a %s: %s", followerAddr, requestString)
           180  
           181  	// Enviar el mensaje al seguidor y recibir la respuesta
           182  	reply, err := l.aAbstractNode.SendMessageSync(followerAddr, requestString)
           183  	if err != nil {
           184  		log.Printf("Error al recibir respuesta de %s: %v", followerAddr, err)
           185  		followError := NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           186  		results <- followError
           187  		return
           188  	}
           189  
           190  	log.Printf("Respuesta recibida de %s: %s", followerAddr, reply)
           191  
           192  	// Deserializar la respuesta JSON
           193  	var response map[string]string
           194  	if err := json.Unmarshal([]byte(reply), &response); err != nil {
           195  		log.Printf("Error al procesar la respuesta de %s: %v", followerAddr, err)
           196  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           197  		return
           198  	}
           199  
           200  	// Calcular la diferencia de tiempo
           201  	endCommTime := time.Now().UnixMilli() // T0
           202  	timeComm := endCommTime - leaderTime
           203  	log.Printf("Tiempo de comunicación: %d ms", timeComm)
           204  
           205  	// Obtener el tiempo local del seguidor
           206  	localTimeStr, ok := response["localTime"]
           207  	if !ok {
           208  		log.Printf("No se encontró el campo 'localTime' en la respuesta de %s", followerAddr)
           209  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           210  		return
           211  	}
           212  
           213  	// Convertir el valor de localTime de string a int64
           214  	localTimeInt64, err := strconv.ParseInt(localTimeStr, 10, 64)
           215  	if err != nil {
           216  		log.Printf("Error al convertir 'localTime' a int64 de %s: %v", followerAddr, err)
           217  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           218  		return
           219  	}
           220  
           221  	// Enviar los resultados al canal
           222  	log.Printf("Tiempo local recibido de %s: %d", followerAddr, localTimeInt64)
           223  	foll := NewFollowerInfo(followerAddr, followerName, localTimeInt64, timeComm, 0)
           224  	foll.SetState(Responded)
           225  	results <- foll
           226  }
           227  
           228  // calculateDeltaTimeDifference calcula la diferencia de tiempo (delta) entre el tiempo local y los tiempos de los seguidores válidos.
           229  func (l *Leader) calculateDeltaTimeDifference() int64 {
           230  	// Log de inicio de la operación de cálculo de la diferencia de tiempo
           231  	log.Println("Calculando la diferencia de tiempo (delta)")
           232  
           233  	// Obtener el tiempo actual del líder
           234  	now := time.Now().UnixMilli()
           235  	var sumTime int64 = 0           // Suma de los tiempos ajustados de los seguidores
           236  	var validFollowersCount int = 0 // Contador de seguidores con respuestas válidas
           237  
           238  	// Recorrer los seguidores exitosos y calcular la diferencia de tiempo para cada uno
           239  	for _, follower := range l.SuccessfulFollowers {
           240  		if follower.DiffTime != int64(^uint64(0)>>1) { // Verificar si el seguidor tiene un tiempo válido (Long.MAX_VALUE en Java)
           241  			followerTime := now + follower.DiffTime // Calcular el tiempo ajustado del seguidor
           242  			sumTime += followerTime                 // Sumar el tiempo ajustado
           243  			validFollowersCount++                   // Incrementar el contador de seguidores válidos
           244  		}
           245  	}
           246  
           247  	// Si se tienen seguidores válidos, calcular la diferencia de tiempo promedio
           248  	if validFollowersCount > 0 {
           249  		newNow := sumTime / int64(validFollowersCount) // Calcular el promedio de los tiempos de los seguidores
           250  		delta := newNow - now                          // Calcular la diferencia de tiempo (delta)
           251  
           252  		// Log de los resultados calculados
           253  		log.Printf("Nuevo tiempo calculado (new_now): %d\n", newNow)
           254  		log.Printf("Diferencia global (δ): %d\n", delta)
           255  
           256  		// Retornar la diferencia de tiempo (delta)
           257  		return delta
           258  	} else {
           259  		// Si no hay seguidores válidos, registrar advertencia y retornar 0
           260  		log.Println("No se han recibido respuestas válidas de los seguidores.")
           261  		return 0
           262  	}
           263  }
           264  
           265  func (l *Leader) callFollowersWithUpdatedTime(delta int64) error {
           266  	log.Printf("Enviando actualización de tiempo a los seguidores con delta: %d", delta)
           267  
           268  	// Crear un canal para gestionar las tareas concurrentes
           269  	ch := make(chan *FollowerInfo, len(l.SuccessfulFollowers))
           270  
           271  	// Usamos un WaitGroup para esperar que todas las goroutines terminen
           272  	var wg sync.WaitGroup
           273  
           274  	// Enviar las tareas en paralelo para cada seguidor
           275  	for _, follower := range l.SuccessfulFollowers {
           276  		wg.Add(1) // Incrementamos el contador del WaitGroup
           277  		go func(follower FollowerInfo) {
           278  			defer wg.Done() // Decrementamos el contador del WaitGroup cuando la goroutine termina
           279  			followerInfo := l.sendTimeUpdateToFollower(follower, delta)
           280  			ch <- followerInfo
           281  		}(*follower)
           282  	}
           283  
           284  	// Iniciar una goroutine para cerrar el canal una vez que todas las goroutines hayan terminado
           285  	go func() {
           286  		wg.Wait() // Esperamos a que todas las goroutines terminen
           287  		close(ch) // Cerramos el canal después de que todas las goroutines hayan enviado sus respuestas
           288  	}()
           289  
           290  	// Procesar las respuestas conforme vayan llegando
           291  	for followerInfo := range ch {
           292  		if followerInfo.State == "TIME_UPDATED" {
           293  			log.Printf("El seguidor %s respondió correctamente al cambio del timer.", followerInfo.Name)
           294  			l.TimeUpdatedFollowers[followerInfo.Name] = followerInfo
           295  		} else {
           296  			log.Printf("El seguidor %s no respondió al cambio de su timer.", followerInfo.Name)
           297  			l.FailedFollowers[followerInfo.Name] = followerInfo
           298  		}
           299  	}
           300  
           301  	return nil
           302  }
           303  
           304  func (l *Leader) sendTimeUpdateToFollower(follower FollowerInfo, delta int64) *FollowerInfo {
           305  
           306  	// Crear el mapa con la solicitud
           307  	request := DeltaRequest{
           308  		Message:    "Modifica el tiempo del sistema de tu servidor con el diferencial.",
           309  		Operation:  "UPDATE_TIME",
           310  		Delta:      delta,
           311  		LeaderAddr: l.aAbstractNode.Address,
           312  	}
           313  
           314  	// Serializar la solicitud a JSON
           315  	jsonRequest, err := json.Marshal(request)
           316  	if err != nil {
           317  		log.Printf("Error al serializar la solicitud para el seguidor %s: %v", follower.Name, err)
           318  		follower.State = TimeErrorSentUpdate
           319  		return &follower
           320  	}
           321  
           322  	requestString := string(jsonRequest)
           323  	log.Printf("Solicitud enviada a %s: %s", follower.GetAddress(), requestString)
           324  	// Enviar la solicitud
           325  	reply, err := l.aAbstractNode.SendMessageSync(follower.GetAddress(), requestString)
           326  	if err != nil {
           327  		log.Printf("Error al recibir respuesta de %s: %v", follower.GetAddress(), err)
           328  		followError := NewFollowerInfo(follower.GetAddress(), follower.GetName(), 0, 0, 0)
           329  		followError.State = TimeErrorSentUpdate
           330  		return followError
           331  	}
           332  
           333  	var response map[string]string
           334  	err = json.Unmarshal([]byte(reply), &response)
           335  	if err != nil {
           336  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", follower.Name, err)
           337  		follower.State = TimeErrorSentUpdate
           338  		return &follower
           339  	}
           340  
           341  	// Registrar la respuesta
           342  	followerName := response["followerName"]
           343  	operation := response["operation"]
           344  	log.Printf("Respuesta de %s: Operación %s exitosa", followerName, operation)
           345  
           346  	follower.State = TimeUpdated
           347  	return &follower
           348  }
           349  func (l *Leader) sendCloseMessagesToFollowers() {
           350  	// Crear un WaitGroup para esperar a que todas las goroutines terminen
           351  	var wg sync.WaitGroup
           352  
           353  	// Canal para recibir los resultados de las goroutines
           354  	resultCh := make(chan string, len(l.TimeUpdatedFollowers))
           355  
           356  	// Enviar mensaje de cierre a cada seguidor de manera concurrente
           357  	for _, follower := range l.TimeUpdatedFollowers {
           358  		wg.Add(1)
           359  		go func(follower FollowerInfo) {
           360  			defer wg.Done()
           361  
           362  			// Enviar el mensaje de cierre
           363  			err := l.sendCloseMessage(follower.Address, follower.Name)
           364  			if err != nil {
           365  				resultCh <- fmt.Sprintf("Error al enviar mensaje de cierre a %s: %s", follower.Name, err)
           366  				return
           367  			}
           368  
           369  			// Simulamos que el mensaje fue enviado exitosamente
           370  			resultCh <- fmt.Sprintf("Mensaje de cierre enviado con éxito a %s", follower.Name)
           371  		}(*follower)
           372  	}
           373  
           374  	// Esperar a que todas las goroutines terminen
           375  	go func() {
           376  		wg.Wait()
           377  		close(resultCh)
           378  	}()
           379  
           380  	// Procesar los resultados a medida que vayan llegando
           381  	for result := range resultCh {
           382  		log.Println(result)
           383  	}
           384  
           385  }
           386  
           387  // SendCloseMessage envía un mensaje de cierre a un seguidor.
           388  // Simulación de la función para enviar mensaje de cierre a un seguidor
           389  func (l *Leader) sendCloseMessage(followerAddress, followerName string) *FollowerInfo {
           390  	log.Printf("Enviando mensaje de cierre a %s...", followerAddress)
           391  
           392  	request := closeRequest{
           393  		Message:    "Cerrar conexión",
           394  		Operation:  "CLOSE",
           395  		LeaderAddr: l.aAbstractNode.Address,
           396  	}
           397  
           398  	// Convertir el mensaje a JSON
           399  	jsonRequest, err := json.Marshal(request)
           400  	if err != nil {
           401  		log.Printf("error al crear mensaje de cierre: %w", err)
           402  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           403  		followError.State = ErrorClose
           404  		return followError
           405  	}
           406  
           407  	// Simulamos el envío del mensaje al seguidor (usando un canal)
           408  	log.Printf("Mensaje de cierre enviado a %s: %s", followerAddress, jsonRequest)
           409  	// Serializar la solicitud a JSON
           410  
           411  	requestString := string(jsonRequest)
           412  	log.Printf("Solicitud enviada a %s: %s", followerAddress, requestString)
           413  	// Enviar la solicitud
           414  	reply, err := l.aAbstractNode.SendMessageSync(followerAddress, requestString)
           415  	if err != nil {
           416  		log.Printf("Error al recibir respuesta de %s: %v", followerAddress, err)
           417  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           418  		followError.State = ErrorClose
           419  		return followError
           420  	}
           421  
           422  	var response map[string]string
           423  	err = json.Unmarshal([]byte(reply), &response)
           424  	if err != nil {
           425  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", followerName, err)
           426  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           427  		followError.State = ErrorClose
           428  		return followError
           429  	}
           430  	// Simulamos una respuesta (en un caso real recibirías la respuesta desde el socket)
           431  	// Aquí se simula un éxito.
           432  	response = map[string]string{
           433  		"followerName": followerAddress,
           434  		"operation":    "CLOSE",
           435  	}
           436  
           437  	// Convertimos la respuesta a JSON
           438  	jsonResponse, err := json.Marshal(response)
           439  	if err != nil {
           440  		log.Printf("error al procesar la respuesta: %w", err)
           441  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           442  		followError.State = ErrorClose
           443  		return followError
           444  	}
           445  
           446  	// Simulamos la recepción de la respuesta (en un caso real, recibirías el mensaje desde el socket)
           447  	log.Printf("Respuesta recibida de %s: %s", followerAddress, jsonResponse)
           448  	follow := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           449  	follow.State = OkClose
           450  	return follow
           451  }
           452  
           453  // PrintResults muestra los resultados del algoritmo.
           454  func (l *Leader) printResults() {
           455  	l.Logger.Println("Resultados del algoritmo Berkeley:")
           456  
           457  	// Mostrar seguidores inalcanzables
           458  	l.Logger.Println("Seguidores inalcanzables:")
           459  	for key, value := range l.UnreachableFollowers {
           460  		l.Logger.Printf("- %s: %v", key, value)
           461  	}
           462  
           463  	// Mostrar seguidores que no respondieron a tiempo
           464  	l.Logger.Println("Seguidores que no respondieron a tiempo:")
           465  	for key, value := range l.NonRespondingFollowers {
           466  		l.Logger.Printf("- %s: %v", key, value)
           467  	}
           468  
           469  	// Mostrar seguidores que respondieron correctamente
           470  	l.Logger.Println("Seguidores que respondieron correctamente:")
           471  	for key, value := range l.SuccessfulFollowers {
           472  		l.Logger.Printf("- %s: %v", key, value)
           473  	}
           474  
           475  	// Mostrar seguidores que actualizaron su tiempo correctamente
           476  	l.Logger.Println("Seguidores que actualizaron su tiempo correctamente:")
           477  	for key, value := range l.TimeUpdatedFollowers {
           478  		l.Logger.Printf("- %s: %v", key, value)
           479  	}
           480  
           481  	// Mostrar seguidores que no pudieron actualizar su tiempo
           482  	l.Logger.Println("Seguidores que no pudieron actualizar su tiempo:")
           483  	for key, value := range l.FailedFollowers {
           484  		l.Logger.Printf("- %s: %v", key, value)
           485  	}
           486  }
           487  func (l *Leader) Close() {
           488  	l.aAbstractNode.Close()
           489  }
           490  
        

        View as plain text

        src/goberkeley/berkeley/leader.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/leader.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  
             7  	"log"
             8  	"strconv"
             9  	"sync"
            10  	"time"
            11  )
            12  
            13  // Mensaje JSON que se envía al seguidor.
            14  type TimeRequest struct {
            15  	Message    string `json:"message"`
            16  	Operation  string `json:"operation"`
            17  	Time       int64  `json:"time"`
            18  	LeaderAddr string `json:"leader_address"`
            19  }
            20  type DeltaRequest struct {
            21  	Message    string `json:"message"`
            22  	Operation  string `json:"operation"`
            23  	Delta      int64  `json:"delta"`
            24  	LeaderAddr string `json:"leader_address"`
            25  }
            26  type closeRequest struct {
            27  	Message    string `json:"message"`
            28  	Operation  string `json:"operation"`
            29  	LeaderAddr string `json:"leader_address"`
            30  }
            31  
            32  // Leader representa el nodo líder en el sistema Berkeley.
            33  type Leader struct {
            34  	aAbstractNode          *AbstractNode
            35  	UnreachableFollowers   map[string]*FollowerInfo
            36  	SuccessfulFollowers    map[string]*FollowerInfo
            37  	NonRespondingFollowers map[string]*FollowerInfo
            38  	TimeUpdatedFollowers   map[string]*FollowerInfo
            39  	FailedFollowers        map[string]*FollowerInfo
            40  	//mu                     sync.Mutex // Mutex para proteger los mapas en accesos concurrentes
            41  	Logger *log.Logger
            42  }
            43  
            44  // HandleProcess implements Handler.
            45  func (l *Leader) HandleProcess(message string) (string, error) {
            46  	panic("unimplemented")
            47  }
            48  
            49  // InitializeLeaderNode crea e inicializa un nuevo nodo líder.
            50  func InitializeLeaderNode(name, address string, timeout time.Duration, nodeAddresses map[string]string) (*Leader, error) {
            51  	// Suponiendo que InitializeNodeWithAddresses crea un nodo base y devuelve un puntero a AbstractNode
            52  	baseNode, err := InitializeNodeWithAddresses(name, address, timeout, nodeAddresses)
            53  	if err != nil {
            54  		return nil, err
            55  	}
            56  
            57  	// Inicializamos el líder, asignando el nodo base y un logger
            58  	leader := &Leader{
            59  		aAbstractNode: baseNode, // Asignamos el puntero a AbstractNode
            60  		Logger:        log.Default(),
            61  	}
            62  	leader.aAbstractNode.Handler = leader
            63  
            64  	return leader, nil
            65  }
            66  func (l *Leader) initStructs() {
            67  	if l.UnreachableFollowers == nil {
            68  		l.UnreachableFollowers = make(map[string]*FollowerInfo)
            69  	}
            70  	if l.SuccessfulFollowers == nil {
            71  		l.SuccessfulFollowers = make(map[string]*FollowerInfo)
            72  	}
            73  	if l.NonRespondingFollowers == nil {
            74  		l.NonRespondingFollowers = make(map[string]*FollowerInfo)
            75  	}
            76  	if l.TimeUpdatedFollowers == nil {
            77  		l.TimeUpdatedFollowers = make(map[string]*FollowerInfo)
            78  	}
            79  	if l.FailedFollowers == nil {
            80  		l.FailedFollowers = make(map[string]*FollowerInfo)
            81  	}
            82  }
            83  
            84  // StartAlgorithm implementa el algoritmo de sincronización Berkeley para el líder.
            85  func (l *Leader) StartAlgorithm() {
            86  	l.Logger.Println("Iniciando algoritmo de sincronización Berkeley...")
            87  	l.initStructs()
            88  	// Simula el envío de solicitudes de tiempo a los seguidores
            89  	l.processFollowers()
            90  
            91  	// Fase 2: Calcular el delta con la media de los tiempos
            92  	log.Println("** Fase 2 **: Calcular el delta con la media de los tiempos")
            93  	delta := l.calculateDeltaTimeDifference()
            94  	if delta != 0 {
            95  		// Paso 3: Actualizar relojes de los seguidores
            96  		log.Println("** Paso 3 **: Llamar a los seguidores para actualizar sus relojes")
            97  		l.callFollowersWithUpdatedTime(delta)
            98  
            99  		// Fase 4: Enviar mensaje de cierre
           100  		log.Println("** Fase 4 **: Enviar mensaje de cierre a los seguidores")
           101  		l.sendCloseMessagesToFollowers()
           102  
           103  		// Fase 5: Mostrar los resultados finales
           104  		log.Println("** Fase 5: Mostrar los resultados de la sincronización")
           105  		l.printResults()
           106  	} else {
           107  		// Se registra esta situación para comprobarlo más adelante en los logs
           108  		log.Println("El resultado del delta es cero por lo que no se envían actualizaciones a ningún seguidor.")
           109  	}
           110  }
           111  func (l *Leader) processFollowers() {
           112  	leaderTime := time.Now().UnixMilli() // T0
           113  	leaderAddr := l.aAbstractNode.Address
           114  
           115  	log.Printf("processFollowers: leaderAddr %s leaderTime %d.", leaderAddr, leaderTime)
           116  
           117  	// Lista de seguidores
           118  	followers := l.aAbstractNode.NodeAddresses
           119  
           120  	// Canal para los resultados
           121  	results := make(chan *FollowerInfo, len(followers))
           122  	var wg sync.WaitGroup
           123  
           124  	// Enviar solicitudes a los seguidores concurrentemente
           125  	for followerName, followerAddr := range followers {
           126  		wg.Add(1)
           127  		go func(name, addr string) {
           128  			defer wg.Done()
           129  			log.Printf("Enviando solicitud de tiempo a %s (%s).", name, addr)
           130  			l.sendTimeRequestToFollower(name, addr, leaderTime, leaderAddr, results)
           131  		}(followerName, followerAddr)
           132  	}
           133  
           134  	// Cerrar el canal una vez que todos los goroutines hayan terminado
           135  	go func() {
           136  		wg.Wait()
           137  		close(results)
           138  	}()
           139  
           140  	// Recoger y procesar los resultados
           141  	for res := range results {
           142  		if res.GetState() == "RESPONDED" {
           143  			// Seguidor que respondió correctamente
           144  			l.SuccessfulFollowers[res.GetName()] = res
           145  			log.Printf("Seguidor %s respondió correctamente con tiempo local: %d ms", res.GetName(), res.GetLocalTime())
           146  		} else if res.GetState() == "TIMEOUT" {
           147  			// Seguidor que no respondió a tiempo
           148  			l.NonRespondingFollowers[res.GetName()] = res
           149  			log.Printf("Seguidor %s no respondió a tiempo.", res.GetName())
           150  		} else {
           151  			// Seguidor que tuvo algún otro problema
           152  			l.FailedFollowers[res.GetName()] = res
           153  			log.Printf("Seguidor %s falló con estado: %s.", res.GetName(), res.GetState())
           154  		}
           155  	}
           156  
           157  	// Log final para indicar que el procesamiento de seguidores ha terminado
           158  	log.Printf("Proceso de seguidores completado. Respuestas procesadas: %d, Fallos: %d.", len(l.SuccessfulFollowers), len(l.NonRespondingFollowers))
           159  }
           160  func (l *Leader) sendTimeRequestToFollower(followerName, followerAddr string, leaderTime int64, leaderAddr string, results chan<- *FollowerInfo) {
           161  	// Crear el mensaje JSON
           162  	request := TimeRequest{
           163  		Message:    "Requesting time sync",
           164  		Operation:  "GET_TIME",
           165  		Time:       leaderTime, //T0
           166  		LeaderAddr: leaderAddr,
           167  	}
           168  
           169  	// Serializar el mensaje en formato JSON
           170  	requestData, err := json.Marshal(request)
           171  	if err != nil {
           172  		log.Printf("Error al serializar la solicitud a JSON: %v", err)
           173  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           174  		return
           175  	}
           176  
           177  	// Convertir el JSON a string
           178  	requestString := string(requestData)
           179  	log.Printf("Solicitud enviada a %s: %s", followerAddr, requestString)
           180  
           181  	// Enviar el mensaje al seguidor y recibir la respuesta
           182  	reply, err := l.aAbstractNode.SendMessageSync(followerAddr, requestString)
           183  	if err != nil {
           184  		log.Printf("Error al recibir respuesta de %s: %v", followerAddr, err)
           185  		followError := NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           186  		results <- followError
           187  		return
           188  	}
           189  
           190  	log.Printf("Respuesta recibida de %s: %s", followerAddr, reply)
           191  
           192  	// Deserializar la respuesta JSON
           193  	var response map[string]string
           194  	if err := json.Unmarshal([]byte(reply), &response); err != nil {
           195  		log.Printf("Error al procesar la respuesta de %s: %v", followerAddr, err)
           196  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           197  		return
           198  	}
           199  
           200  	// Calcular la diferencia de tiempo
           201  	endCommTime := time.Now().UnixMilli() // T0
           202  	timeComm := endCommTime - leaderTime
           203  	log.Printf("Tiempo de comunicación: %d ms", timeComm)
           204  
           205  	// Obtener el tiempo local del seguidor
           206  	localTimeStr, ok := response["localTime"]
           207  	if !ok {
           208  		log.Printf("No se encontró el campo 'localTime' en la respuesta de %s", followerAddr)
           209  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           210  		return
           211  	}
           212  
           213  	// Convertir el valor de localTime de string a int64
           214  	localTimeInt64, err := strconv.ParseInt(localTimeStr, 10, 64)
           215  	if err != nil {
           216  		log.Printf("Error al convertir 'localTime' a int64 de %s: %v", followerAddr, err)
           217  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           218  		return
           219  	}
           220  
           221  	// Enviar los resultados al canal
           222  	log.Printf("Tiempo local recibido de %s: %d", followerAddr, localTimeInt64)
           223  	foll := NewFollowerInfo(followerAddr, followerName, localTimeInt64, timeComm, 0)
           224  	foll.SetState(Responded)
           225  	results <- foll
           226  }
           227  
           228  // calculateDeltaTimeDifference calcula la diferencia de tiempo (delta) entre el tiempo local y los tiempos de los seguidores válidos.
           229  func (l *Leader) calculateDeltaTimeDifference() int64 {
           230  	// Log de inicio de la operación de cálculo de la diferencia de tiempo
           231  	log.Println("Calculando la diferencia de tiempo (delta)")
           232  
           233  	// Obtener el tiempo actual del líder
           234  	now := time.Now().UnixMilli()
           235  	var sumTime int64 = 0           // Suma de los tiempos ajustados de los seguidores
           236  	var validFollowersCount int = 0 // Contador de seguidores con respuestas válidas
           237  
           238  	// Recorrer los seguidores exitosos y calcular la diferencia de tiempo para cada uno
           239  	for _, follower := range l.SuccessfulFollowers {
           240  		if follower.DiffTime != int64(^uint64(0)>>1) { // Verificar si el seguidor tiene un tiempo válido (Long.MAX_VALUE en Java)
           241  			followerTime := now + follower.DiffTime // Calcular el tiempo ajustado del seguidor
           242  			sumTime += followerTime                 // Sumar el tiempo ajustado
           243  			validFollowersCount++                   // Incrementar el contador de seguidores válidos
           244  		}
           245  	}
           246  
           247  	// Si se tienen seguidores válidos, calcular la diferencia de tiempo promedio
           248  	if validFollowersCount > 0 {
           249  		newNow := sumTime / int64(validFollowersCount) // Calcular el promedio de los tiempos de los seguidores
           250  		delta := newNow - now                          // Calcular la diferencia de tiempo (delta)
           251  
           252  		// Log de los resultados calculados
           253  		log.Printf("Nuevo tiempo calculado (new_now): %d\n", newNow)
           254  		log.Printf("Diferencia global (δ): %d\n", delta)
           255  
           256  		// Retornar la diferencia de tiempo (delta)
           257  		return delta
           258  	} else {
           259  		// Si no hay seguidores válidos, registrar advertencia y retornar 0
           260  		log.Println("No se han recibido respuestas válidas de los seguidores.")
           261  		return 0
           262  	}
           263  }
           264  
           265  func (l *Leader) callFollowersWithUpdatedTime(delta int64) error {
           266  	log.Printf("Enviando actualización de tiempo a los seguidores con delta: %d", delta)
           267  
           268  	// Crear un canal para gestionar las tareas concurrentes
           269  	ch := make(chan *FollowerInfo, len(l.SuccessfulFollowers))
           270  
           271  	// Usamos un WaitGroup para esperar que todas las goroutines terminen
           272  	var wg sync.WaitGroup
           273  
           274  	// Enviar las tareas en paralelo para cada seguidor
           275  	for _, follower := range l.SuccessfulFollowers {
           276  		wg.Add(1) // Incrementamos el contador del WaitGroup
           277  		go func(follower FollowerInfo) {
           278  			defer wg.Done() // Decrementamos el contador del WaitGroup cuando la goroutine termina
           279  			followerInfo := l.sendTimeUpdateToFollower(follower, delta)
           280  			ch <- followerInfo
           281  		}(*follower)
           282  	}
           283  
           284  	// Iniciar una goroutine para cerrar el canal una vez que todas las goroutines hayan terminado
           285  	go func() {
           286  		wg.Wait() // Esperamos a que todas las goroutines terminen
           287  		close(ch) // Cerramos el canal después de que todas las goroutines hayan enviado sus respuestas
           288  	}()
           289  
           290  	// Procesar las respuestas conforme vayan llegando
           291  	for followerInfo := range ch {
           292  		if followerInfo.State == "TIME_UPDATED" {
           293  			log.Printf("El seguidor %s respondió correctamente al cambio del timer.", followerInfo.Name)
           294  			l.TimeUpdatedFollowers[followerInfo.Name] = followerInfo
           295  		} else {
           296  			log.Printf("El seguidor %s no respondió al cambio de su timer.", followerInfo.Name)
           297  			l.FailedFollowers[followerInfo.Name] = followerInfo
           298  		}
           299  	}
           300  
           301  	return nil
           302  }
           303  
           304  func (l *Leader) sendTimeUpdateToFollower(follower FollowerInfo, delta int64) *FollowerInfo {
           305  
           306  	// Crear el mapa con la solicitud
           307  	request := DeltaRequest{
           308  		Message:    "Modifica el tiempo del sistema de tu servidor con el diferencial.",
           309  		Operation:  "UPDATE_TIME",
           310  		Delta:      delta,
           311  		LeaderAddr: l.aAbstractNode.Address,
           312  	}
           313  
           314  	// Serializar la solicitud a JSON
           315  	jsonRequest, err := json.Marshal(request)
           316  	if err != nil {
           317  		log.Printf("Error al serializar la solicitud para el seguidor %s: %v", follower.Name, err)
           318  		follower.State = TimeErrorSentUpdate
           319  		return &follower
           320  	}
           321  
           322  	requestString := string(jsonRequest)
           323  	log.Printf("Solicitud enviada a %s: %s", follower.GetAddress(), requestString)
           324  	// Enviar la solicitud
           325  	reply, err := l.aAbstractNode.SendMessageSync(follower.GetAddress(), requestString)
           326  	if err != nil {
           327  		log.Printf("Error al recibir respuesta de %s: %v", follower.GetAddress(), err)
           328  		followError := NewFollowerInfo(follower.GetAddress(), follower.GetName(), 0, 0, 0)
           329  		followError.State = TimeErrorSentUpdate
           330  		return followError
           331  	}
           332  
           333  	var response map[string]string
           334  	err = json.Unmarshal([]byte(reply), &response)
           335  	if err != nil {
           336  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", follower.Name, err)
           337  		follower.State = TimeErrorSentUpdate
           338  		return &follower
           339  	}
           340  
           341  	// Registrar la respuesta
           342  	followerName := response["followerName"]
           343  	operation := response["operation"]
           344  	log.Printf("Respuesta de %s: Operación %s exitosa", followerName, operation)
           345  
           346  	follower.State = TimeUpdated
           347  	return &follower
           348  }
           349  func (l *Leader) sendCloseMessagesToFollowers() {
           350  	// Crear un WaitGroup para esperar a que todas las goroutines terminen
           351  	var wg sync.WaitGroup
           352  
           353  	// Canal para recibir los resultados de las goroutines
           354  	resultCh := make(chan string, len(l.TimeUpdatedFollowers))
           355  
           356  	// Enviar mensaje de cierre a cada seguidor de manera concurrente
           357  	for _, follower := range l.TimeUpdatedFollowers {
           358  		wg.Add(1)
           359  		go func(follower FollowerInfo) {
           360  			defer wg.Done()
           361  
           362  			// Enviar el mensaje de cierre
           363  			err := l.sendCloseMessage(follower.Address, follower.Name)
           364  			if err != nil {
           365  				resultCh <- fmt.Sprintf("Error al enviar mensaje de cierre a %s: %s", follower.Name, err)
           366  				return
           367  			}
           368  
           369  			// Simulamos que el mensaje fue enviado exitosamente
           370  			resultCh <- fmt.Sprintf("Mensaje de cierre enviado con éxito a %s", follower.Name)
           371  		}(*follower)
           372  	}
           373  
           374  	// Esperar a que todas las goroutines terminen
           375  	go func() {
           376  		wg.Wait()
           377  		close(resultCh)
           378  	}()
           379  
           380  	// Procesar los resultados a medida que vayan llegando
           381  	for result := range resultCh {
           382  		log.Println(result)
           383  	}
           384  
           385  }
           386  
           387  // SendCloseMessage envía un mensaje de cierre a un seguidor.
           388  // Simulación de la función para enviar mensaje de cierre a un seguidor
           389  func (l *Leader) sendCloseMessage(followerAddress, followerName string) *FollowerInfo {
           390  	log.Printf("Enviando mensaje de cierre a %s...", followerAddress)
           391  
           392  	request := closeRequest{
           393  		Message:    "Cerrar conexión",
           394  		Operation:  "CLOSE",
           395  		LeaderAddr: l.aAbstractNode.Address,
           396  	}
           397  
           398  	// Convertir el mensaje a JSON
           399  	jsonRequest, err := json.Marshal(request)
           400  	if err != nil {
           401  		log.Printf("error al crear mensaje de cierre: %w", err)
           402  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           403  		followError.State = ErrorClose
           404  		return followError
           405  	}
           406  
           407  	// Simulamos el envío del mensaje al seguidor (usando un canal)
           408  	log.Printf("Mensaje de cierre enviado a %s: %s", followerAddress, jsonRequest)
           409  	// Serializar la solicitud a JSON
           410  
           411  	requestString := string(jsonRequest)
           412  	log.Printf("Solicitud enviada a %s: %s", followerAddress, requestString)
           413  	// Enviar la solicitud
           414  	reply, err := l.aAbstractNode.SendMessageSync(followerAddress, requestString)
           415  	if err != nil {
           416  		log.Printf("Error al recibir respuesta de %s: %v", followerAddress, err)
           417  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           418  		followError.State = ErrorClose
           419  		return followError
           420  	}
           421  
           422  	var response map[string]string
           423  	err = json.Unmarshal([]byte(reply), &response)
           424  	if err != nil {
           425  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", followerName, err)
           426  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           427  		followError.State = ErrorClose
           428  		return followError
           429  	}
           430  	// Simulamos una respuesta (en un caso real recibirías la respuesta desde el socket)
           431  	// Aquí se simula un éxito.
           432  	response = map[string]string{
           433  		"followerName": followerAddress,
           434  		"operation":    "CLOSE",
           435  	}
           436  
           437  	// Convertimos la respuesta a JSON
           438  	jsonResponse, err := json.Marshal(response)
           439  	if err != nil {
           440  		log.Printf("error al procesar la respuesta: %w", err)
           441  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           442  		followError.State = ErrorClose
           443  		return followError
           444  	}
           445  
           446  	// Simulamos la recepción de la respuesta (en un caso real, recibirías el mensaje desde el socket)
           447  	log.Printf("Respuesta recibida de %s: %s", followerAddress, jsonResponse)
           448  	follow := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           449  	follow.State = OkClose
           450  	return follow
           451  }
           452  
           453  // PrintResults muestra los resultados del algoritmo.
           454  func (l *Leader) printResults() {
           455  	l.Logger.Println("Resultados del algoritmo Berkeley:")
           456  
           457  	// Mostrar seguidores inalcanzables
           458  	l.Logger.Println("Seguidores inalcanzables:")
           459  	for key, value := range l.UnreachableFollowers {
           460  		l.Logger.Printf("- %s: %v", key, value)
           461  	}
           462  
           463  	// Mostrar seguidores que no respondieron a tiempo
           464  	l.Logger.Println("Seguidores que no respondieron a tiempo:")
           465  	for key, value := range l.NonRespondingFollowers {
           466  		l.Logger.Printf("- %s: %v", key, value)
           467  	}
           468  
           469  	// Mostrar seguidores que respondieron correctamente
           470  	l.Logger.Println("Seguidores que respondieron correctamente:")
           471  	for key, value := range l.SuccessfulFollowers {
           472  		l.Logger.Printf("- %s: %v", key, value)
           473  	}
           474  
           475  	// Mostrar seguidores que actualizaron su tiempo correctamente
           476  	l.Logger.Println("Seguidores que actualizaron su tiempo correctamente:")
           477  	for key, value := range l.TimeUpdatedFollowers {
           478  		l.Logger.Printf("- %s: %v", key, value)
           479  	}
           480  
           481  	// Mostrar seguidores que no pudieron actualizar su tiempo
           482  	l.Logger.Println("Seguidores que no pudieron actualizar su tiempo:")
           483  	for key, value := range l.FailedFollowers {
           484  		l.Logger.Printf("- %s: %v", key, value)
           485  	}
           486  }
           487  func (l *Leader) Close() {
           488  	l.aAbstractNode.Close()
           489  }
           490  
        

        View as plain text

        src/goberkeley/berkeley/config.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/config.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  	"os"
             7  	"time"
             8  )
             9  
            10  type LeaderConfig struct {
            11  	Name    string `json:"name"`
            12  	Address string `json:"address"`
            13  }
            14  
            15  type FollowerConfig struct {
            16  	Name    string `json:"name"`
            17  	Address string `json:"address"`
            18  }
            19  
            20  type Config struct {
            21  	Leader    LeaderConfig     `json:"leader"`
            22  	Followers []FollowerConfig `json:"followers"`
            23  	Timeout   time.Duration    `json:"timeout"`
            24  }
            25  
            26  func LoadConfig(filepath string) *Config {
            27  	// Abrir el archivo JSON
            28  	file, err := os.Open(filepath)
            29  	if err != nil {
            30  		fmt.Println("Error abriendo el archivo:", err)
            31  		return nil
            32  	}
            33  	defer file.Close()
            34  
            35  	// Decodificar el JSON en la estructura Config
            36  	var config Config
            37  	decoder := json.NewDecoder(file)
            38  	if err := decoder.Decode(&config); err != nil {
            39  		fmt.Println("Error decodificando JSON:", err)
            40  		return nil
            41  	}
            42  
            43  	// Imprimir la configuración cargada
            44  	fmt.Printf("Líder: %s (%s)\n", config.Leader.Name, config.Leader.Address)
            45  	for _, follower := range config.Followers {
            46  		fmt.Printf("Seguidor: %s (%s)\n", follower.Name, follower.Address)
            47  	}
            48  	fmt.Printf("Timeout: %d ms\n", config.Timeout)
            49  
            50  	return &config
            51  }
            52  
        

        View as plain text

        src/goberkeley/berkeley/logger_manager.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/logger_manager.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"github.com/sirupsen/logrus"
             5  	"reflect"
             6  )
             7  
             8  // LoggerManager es responsable de gestionar los loggers para las clases que lo invocan.
             9  type LoggerManager struct{}
            10  
            11  // GetLogger obtiene el logger correspondiente a la clase que invoca este método.
            12  func (LoggerManager) GetLogger(clazz interface{}) *logrus.Logger {
            13  	// Se usa el nombre de la clase (tipo) como parte del nombre del logger.
            14  	logger := logrus.New()
            15  
            16  	// Se asigna el nombre del tipo (nombre de la clase)
            17  	logger.SetFormatter(&logrus.TextFormatter{
            18  		FullTimestamp: true,
            19  	})
            20  	logger.SetLevel(logrus.InfoLevel)
            21  
            22  	className := reflect.TypeOf(clazz).Name()
            23  	logger.Infof("Logger for %s initialized.", className)
            24  
            25  	return logger
            26  }
            27  
        

        View as plain text

        src/goberkeley/berkeley/logger_manager.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/logger_manager.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"github.com/sirupsen/logrus"
             5  	"reflect"
             6  )
             7  
             8  // LoggerManager es responsable de gestionar los loggers para las clases que lo invocan.
             9  type LoggerManager struct{}
            10  
            11  // GetLogger obtiene el logger correspondiente a la clase que invoca este método.
            12  func (LoggerManager) GetLogger(clazz interface{}) *logrus.Logger {
            13  	// Se usa el nombre de la clase (tipo) como parte del nombre del logger.
            14  	logger := logrus.New()
            15  
            16  	// Se asigna el nombre del tipo (nombre de la clase)
            17  	logger.SetFormatter(&logrus.TextFormatter{
            18  		FullTimestamp: true,
            19  	})
            20  	logger.SetLevel(logrus.InfoLevel)
            21  
            22  	className := reflect.TypeOf(clazz).Name()
            23  	logger.Infof("Logger for %s initialized.", className)
            24  
            25  	return logger
            26  }
            27  
        

        View as plain text

        logrus - Go Documentation Server
        ...

        Package logrus

        import "github.com/sirupsen/logrus"
        Overview
        Index
        Examples
        Subdirectories

        Overview ▾

        Package logrus is a structured logger for Go, completely API compatible with the standard library logger.

        The simplest way to use Logrus is simply the package-level exported logger:

        package main
        
        import (
          log "github.com/sirupsen/logrus"
        )
        
        func main() {
          log.WithFields(log.Fields{
            "animal": "walrus",
            "number": 1,
            "size":   10,
          }).Info("A walrus appears")
        }
        

        Output:

        time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
        

        For a full guide visit https://github.com/sirupsen/logrus

        Example (Basic)

        Code:

        var log = logrus.New()
        log.Formatter = new(logrus.JSONFormatter)
        log.Formatter = new(logrus.TextFormatter)                     //default
        log.Formatter.(*logrus.TextFormatter).DisableColors = true    // remove colors
        log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output
        log.Level = logrus.TraceLevel
        log.Out = os.Stdout
        
        // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
        // if err == nil {
        // 	log.Out = file
        // } else {
        // 	log.Info("Failed to log to file, using default stderr")
        // }
        
        defer func() {
            err := recover()
            if err != nil {
                entry := err.(*logrus.Entry)
                log.WithFields(logrus.Fields{
                    "omg":         true,
                    "err_animal":  entry.Data["animal"],
                    "err_size":    entry.Data["size"],
                    "err_level":   entry.Level,
                    "err_message": entry.Message,
                    "number":      100,
                }).Error("The ice breaks!") // or use Fatal() to force the process to exit with a nonzero code
            }
        }()
        
        log.WithFields(logrus.Fields{
            "animal": "walrus",
            "number": 0,
        }).Trace("Went to the beach")
        
        log.WithFields(logrus.Fields{
            "animal": "walrus",
            "number": 8,
        }).Debug("Started observing beach")
        
        log.WithFields(logrus.Fields{
            "animal": "walrus",
            "size":   10,
        }).Info("A group of walrus emerges from the ocean")
        
        log.WithFields(logrus.Fields{
            "omg":    true,
            "number": 122,
        }).Warn("The group's number increased tremendously!")
        
        log.WithFields(logrus.Fields{
            "temperature": -4,
        }).Debug("Temperature changes")
        
        log.WithFields(logrus.Fields{
            "animal": "orca",
            "size":   9009,
        }).Panic("It's over 9000!")
        
        

        Output:

        level=trace msg="Went to the beach" animal=walrus number=0
        level=debug msg="Started observing beach" animal=walrus number=8
        level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
        level=warning msg="The group's number increased tremendously!" number=122 omg=true
        level=debug msg="Temperature changes" temperature=-4
        level=panic msg="It's over 9000!" animal=orca size=9009
        level=error msg="The ice breaks!" err_animal=orca err_level=panic err_message="It's over 9000!" err_size=9009 number=100 omg=true
        

        Example (Hook)

        An example on how to use a hook

        Code:

        var log = logrus.New()
        log.Formatter = new(logrus.TextFormatter)                     // default
        log.Formatter.(*logrus.TextFormatter).DisableColors = true    // remove colors
        log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output
        if sl, err := slhooks.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, ""); err == nil {
            log.Hooks.Add(sl)
        }
        log.Out = os.Stdout
        
        log.WithFields(logrus.Fields{
            "animal": "walrus",
            "size":   10,
        }).Info("A group of walrus emerges from the ocean")
        
        log.WithFields(logrus.Fields{
            "omg":    true,
            "number": 122,
        }).Warn("The group's number increased tremendously!")
        
        log.WithFields(logrus.Fields{
            "omg":    true,
            "number": 100,
        }).Error("The ice breaks!")
        
        

        Output:

        level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
        level=warning msg="The group's number increased tremendously!" number=122 omg=true
        level=error msg="The ice breaks!" number=100 omg=true
        

        Index ▾

        Constants
        Variables
        func AddHook(hook Hook)
        func Debug(args ...interface{})
        func DebugFn(fn LogFunction)
        func Debugf(format string, args ...interface{})
        func Debugln(args ...interface{})
        func DeferExitHandler(handler func())
        func Error(args ...interface{})
        func ErrorFn(fn LogFunction)
        func Errorf(format string, args ...interface{})
        func Errorln(args ...interface{})
        func Exit(code int)
        func Fatal(args ...interface{})
        func FatalFn(fn LogFunction)
        func Fatalf(format string, args ...interface{})
        func Fatalln(args ...interface{})
        func Info(args ...interface{})
        func InfoFn(fn LogFunction)
        func Infof(format string, args ...interface{})
        func Infoln(args ...interface{})
        func IsLevelEnabled(level Level) bool
        func Panic(args ...interface{})
        func PanicFn(fn LogFunction)
        func Panicf(format string, args ...interface{})
        func Panicln(args ...interface{})
        func Print(args ...interface{})
        func PrintFn(fn LogFunction)
        func Printf(format string, args ...interface{})
        func Println(args ...interface{})
        func RegisterExitHandler(handler func())
        func SetBufferPool(bp BufferPool)
        func SetFormatter(formatter Formatter)
        func SetLevel(level Level)
        func SetOutput(out io.Writer)
        func SetReportCaller(include bool)
        func Trace(args ...interface{})
        func TraceFn(fn LogFunction)
        func Tracef(format string, args ...interface{})
        func Traceln(args ...interface{})
        func Warn(args ...interface{})
        func WarnFn(fn LogFunction)
        func Warnf(format string, args ...interface{})
        func Warning(args ...interface{})
        func WarningFn(fn LogFunction)
        func Warningf(format string, args ...interface{})
        func Warningln(args ...interface{})
        func Warnln(args ...interface{})
        type BufferPool
        type Entry
            func NewEntry(logger *Logger) *Entry
            func WithContext(ctx context.Context) *Entry
            func WithError(err error) *Entry
            func WithField(key string, value interface{}) *Entry
            func WithFields(fields Fields) *Entry
            func WithTime(t time.Time) *Entry
            func (entry *Entry) Bytes() ([]byte, error)
            func (entry *Entry) Debug(args ...interface{})
            func (entry *Entry) Debugf(format string, args ...interface{})
            func (entry *Entry) Debugln(args ...interface{})
            func (entry *Entry) Dup() *Entry
            func (entry *Entry) Error(args ...interface{})
            func (entry *Entry) Errorf(format string, args ...interface{})
            func (entry *Entry) Errorln(args ...interface{})
            func (entry *Entry) Fatal(args ...interface{})
            func (entry *Entry) Fatalf(format string, args ...interface{})
            func (entry *Entry) Fatalln(args ...interface{})
            func (entry Entry) HasCaller() (has bool)
            func (entry *Entry) Info(args ...interface{})
            func (entry *Entry) Infof(format string, args ...interface{})
            func (entry *Entry) Infoln(args ...interface{})
            func (entry *Entry) Log(level Level, args ...interface{})
            func (entry *Entry) Logf(level Level, format string, args ...interface{})
            func (entry *Entry) Logln(level Level, args ...interface{})
            func (entry *Entry) Panic(args ...interface{})
            func (entry *Entry) Panicf(format string, args ...interface{})
            func (entry *Entry) Panicln(args ...interface{})
            func (entry *Entry) Print(args ...interface{})
            func (entry *Entry) Printf(format string, args ...interface{})
            func (entry *Entry) Println(args ...interface{})
            func (entry *Entry) String() (string, error)
            func (entry *Entry) Trace(args ...interface{})
            func (entry *Entry) Tracef(format string, args ...interface{})
            func (entry *Entry) Traceln(args ...interface{})
            func (entry *Entry) Warn(args ...interface{})
            func (entry *Entry) Warnf(format string, args ...interface{})
            func (entry *Entry) Warning(args ...interface{})
            func (entry *Entry) Warningf(format string, args ...interface{})
            func (entry *Entry) Warningln(args ...interface{})
            func (entry *Entry) Warnln(args ...interface{})
            func (entry *Entry) WithContext(ctx context.Context) *Entry
            func (entry *Entry) WithError(err error) *Entry
            func (entry *Entry) WithField(key string, value interface{}) *Entry
            func (entry *Entry) WithFields(fields Fields) *Entry
            func (entry *Entry) WithTime(t time.Time) *Entry
            func (entry *Entry) Writer() *io.PipeWriter
            func (entry *Entry) WriterLevel(level Level) *io.PipeWriter
        type Ext1FieldLogger
        type FieldLogger
        type FieldMap
        type Fields
        type Formatter
        type Hook
        type JSONFormatter
            func (f *JSONFormatter) Format(entry *Entry) ([]byte, error)
        type Level
            func GetLevel() Level
            func ParseLevel(lvl string) (Level, error)
            func (level Level) MarshalText() ([]byte, error)
            func (level Level) String() string
            func (level *Level) UnmarshalText(text []byte) error
        type LevelHooks
            func (hooks LevelHooks) Add(hook Hook)
            func (hooks LevelHooks) Fire(level Level, entry *Entry) error
        type LogFunction
        type Logger
            func New() *Logger
            func StandardLogger() *Logger
            func (logger *Logger) AddHook(hook Hook)
            func (logger *Logger) Debug(args ...interface{})
            func (logger *Logger) DebugFn(fn LogFunction)
            func (logger *Logger) Debugf(format string, args ...interface{})
            func (logger *Logger) Debugln(args ...interface{})
            func (logger *Logger) Error(args ...interface{})
            func (logger *Logger) ErrorFn(fn LogFunction)
            func (logger *Logger) Errorf(format string, args ...interface{})
            func (logger *Logger) Errorln(args ...interface{})
            func (logger *Logger) Exit(code int)
            func (logger *Logger) Fatal(args ...interface{})
            func (logger *Logger) FatalFn(fn LogFunction)
            func (logger *Logger) Fatalf(format string, args ...interface{})
            func (logger *Logger) Fatalln(args ...interface{})
            func (logger *Logger) GetLevel() Level
            func (logger *Logger) Info(args ...interface{})
            func (logger *Logger) InfoFn(fn LogFunction)
            func (logger *Logger) Infof(format string, args ...interface{})
            func (logger *Logger) Infoln(args ...interface{})
            func (logger *Logger) IsLevelEnabled(level Level) bool
            func (logger *Logger) Log(level Level, args ...interface{})
            func (logger *Logger) LogFn(level Level, fn LogFunction)
            func (logger *Logger) Logf(level Level, format string, args ...interface{})
            func (logger *Logger) Logln(level Level, args ...interface{})
            func (logger *Logger) Panic(args ...interface{})
            func (logger *Logger) PanicFn(fn LogFunction)
            func (logger *Logger) Panicf(format string, args ...interface{})
            func (logger *Logger) Panicln(args ...interface{})
            func (logger *Logger) Print(args ...interface{})
            func (logger *Logger) PrintFn(fn LogFunction)
            func (logger *Logger) Printf(format string, args ...interface{})
            func (logger *Logger) Println(args ...interface{})
            func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks
            func (logger *Logger) SetBufferPool(pool BufferPool)
            func (logger *Logger) SetFormatter(formatter Formatter)
            func (logger *Logger) SetLevel(level Level)
            func (logger *Logger) SetNoLock()
            func (logger *Logger) SetOutput(output io.Writer)
            func (logger *Logger) SetReportCaller(reportCaller bool)
            func (logger *Logger) Trace(args ...interface{})
            func (logger *Logger) TraceFn(fn LogFunction)
            func (logger *Logger) Tracef(format string, args ...interface{})
            func (logger *Logger) Traceln(args ...interface{})
            func (logger *Logger) Warn(args ...interface{})
            func (logger *Logger) WarnFn(fn LogFunction)
            func (logger *Logger) Warnf(format string, args ...interface{})
            func (logger *Logger) Warning(args ...interface{})
            func (logger *Logger) WarningFn(fn LogFunction)
            func (logger *Logger) Warningf(format string, args ...interface{})
            func (logger *Logger) Warningln(args ...interface{})
            func (logger *Logger) Warnln(args ...interface{})
            func (logger *Logger) WithContext(ctx context.Context) *Entry
            func (logger *Logger) WithError(err error) *Entry
            func (logger *Logger) WithField(key string, value interface{}) *Entry
            func (logger *Logger) WithFields(fields Fields) *Entry
            func (logger *Logger) WithTime(t time.Time) *Entry
            func (logger *Logger) Writer() *io.PipeWriter
            func (logger *Logger) WriterLevel(level Level) *io.PipeWriter
        type MutexWrap
            func (mw *MutexWrap) Disable()
            func (mw *MutexWrap) Lock()
            func (mw *MutexWrap) Unlock()
        type StdLogger
        type TextFormatter
            func (f *TextFormatter) Format(entry *Entry) ([]byte, error)

        Package files

        alt_exit.go buffer_pool.go doc.go entry.go exported.go formatter.go hooks.go json_formatter.go logger.go logrus.go terminal_check_notappengine.go terminal_check_unix.go text_formatter.go writer.go

        Constants

        Default key names for the default fields

        const (
            FieldKeyMsg         = "msg"
            FieldKeyLevel       = "level"
            FieldKeyTime        = "time"
            FieldKeyLogrusError = "logrus_error"
            FieldKeyFunc        = "func"
            FieldKeyFile        = "file"
        )

        Variables

        A constant exposing all logging levels

        var AllLevels = []Level{
            PanicLevel,
            FatalLevel,
            ErrorLevel,
            WarnLevel,
            InfoLevel,
            DebugLevel,
            TraceLevel,
        }

        Defines the key when adding errors using WithError.

        var ErrorKey = "error"

        func AddHook

        func AddHook(hook Hook)

        AddHook adds a hook to the standard logger hooks.

        func Debug

        func Debug(args ...interface{})

        Debug logs a message at level Debug on the standard logger.

        func DebugFn

        func DebugFn(fn LogFunction)

        DebugFn logs a message from a func at level Debug on the standard logger.

        func Debugf

        func Debugf(format string, args ...interface{})

        Debugf logs a message at level Debug on the standard logger.

        func Debugln

        func Debugln(args ...interface{})

        Debugln logs a message at level Debug on the standard logger.

        func DeferExitHandler

        func DeferExitHandler(handler func())

        DeferExitHandler prepends a Logrus Exit handler to the list of handlers, call logrus.Exit to invoke all handlers. The handlers will also be invoked when any Fatal log entry is made.

        This method is useful when a caller wishes to use logrus to log a fatal message but also needs to gracefully shutdown. An example usecase could be closing database connections, or sending a alert that the application is closing.

        func Error

        func Error(args ...interface{})

        Error logs a message at level Error on the standard logger.

        func ErrorFn

        func ErrorFn(fn LogFunction)

        ErrorFn logs a message from a func at level Error on the standard logger.

        func Errorf

        func Errorf(format string, args ...interface{})

        Errorf logs a message at level Error on the standard logger.

        func Errorln

        func Errorln(args ...interface{})

        Errorln logs a message at level Error on the standard logger.

        func Exit

        func Exit(code int)

        Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)

        func Fatal

        func Fatal(args ...interface{})

        Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1.

        func FatalFn

        func FatalFn(fn LogFunction)

        FatalFn logs a message from a func at level Fatal on the standard logger then the process will exit with status set to 1.

        func Fatalf

        func Fatalf(format string, args ...interface{})

        Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1.

        func Fatalln

        func Fatalln(args ...interface{})

        Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1.

        func Info

        func Info(args ...interface{})

        Info logs a message at level Info on the standard logger.

        func InfoFn

        func InfoFn(fn LogFunction)

        InfoFn logs a message from a func at level Info on the standard logger.

        func Infof

        func Infof(format string, args ...interface{})

        Infof logs a message at level Info on the standard logger.

        func Infoln

        func Infoln(args ...interface{})

        Infoln logs a message at level Info on the standard logger.

        func IsLevelEnabled

        func IsLevelEnabled(level Level) bool

        IsLevelEnabled checks if the log level of the standard logger is greater than the level param

        func Panic

        func Panic(args ...interface{})

        Panic logs a message at level Panic on the standard logger.

        func PanicFn

        func PanicFn(fn LogFunction)

        PanicFn logs a message from a func at level Panic on the standard logger.

        func Panicf

        func Panicf(format string, args ...interface{})

        Panicf logs a message at level Panic on the standard logger.

        func Panicln

        func Panicln(args ...interface{})

        Panicln logs a message at level Panic on the standard logger.

        func Print

        func Print(args ...interface{})

        Print logs a message at level Info on the standard logger.

        func PrintFn

        func PrintFn(fn LogFunction)

        PrintFn logs a message from a func at level Info on the standard logger.

        func Printf

        func Printf(format string, args ...interface{})

        Printf logs a message at level Info on the standard logger.

        func Println

        func Println(args ...interface{})

        Println logs a message at level Info on the standard logger.

        func RegisterExitHandler

        func RegisterExitHandler(handler func())

        RegisterExitHandler appends a Logrus Exit handler to the list of handlers, call logrus.Exit to invoke all handlers. The handlers will also be invoked when any Fatal log entry is made.

        This method is useful when a caller wishes to use logrus to log a fatal message but also needs to gracefully shutdown. An example usecase could be closing database connections, or sending a alert that the application is closing.

        func SetBufferPool

        func SetBufferPool(bp BufferPool)

        SetBufferPool allows to replace the default logrus buffer pool to better meets the specific needs of an application.

        func SetFormatter

        func SetFormatter(formatter Formatter)

        SetFormatter sets the standard logger formatter.

        func SetLevel

        func SetLevel(level Level)

        SetLevel sets the standard logger level.

        func SetOutput

        func SetOutput(out io.Writer)

        SetOutput sets the standard logger output.

        func SetReportCaller

        func SetReportCaller(include bool)

        SetReportCaller sets whether the standard logger will include the calling method as a field.

        func Trace

        func Trace(args ...interface{})

        Trace logs a message at level Trace on the standard logger.

        func TraceFn

        func TraceFn(fn LogFunction)

        TraceFn logs a message from a func at level Trace on the standard logger.

        func Tracef

        func Tracef(format string, args ...interface{})

        Tracef logs a message at level Trace on the standard logger.

        func Traceln

        func Traceln(args ...interface{})

        Traceln logs a message at level Trace on the standard logger.

        func Warn

        func Warn(args ...interface{})

        Warn logs a message at level Warn on the standard logger.

        func WarnFn

        func WarnFn(fn LogFunction)

        WarnFn logs a message from a func at level Warn on the standard logger.

        func Warnf

        func Warnf(format string, args ...interface{})

        Warnf logs a message at level Warn on the standard logger.

        func Warning

        func Warning(args ...interface{})

        Warning logs a message at level Warn on the standard logger.

        func WarningFn

        func WarningFn(fn LogFunction)

        WarningFn logs a message from a func at level Warn on the standard logger.

        func Warningf

        func Warningf(format string, args ...interface{})

        Warningf logs a message at level Warn on the standard logger.

        func Warningln

        func Warningln(args ...interface{})

        Warningln logs a message at level Warn on the standard logger.

        func Warnln

        func Warnln(args ...interface{})

        Warnln logs a message at level Warn on the standard logger.

        type BufferPool

        type BufferPool interface {
            Put(*bytes.Buffer)
            Get() *bytes.Buffer
        }

        type Entry

        An entry is the final or intermediate Logrus logging entry. It contains all the fields passed with WithField{,s}. It's finally logged when Trace, Debug, Info, Warn, Error, Fatal or Panic is called on it. These objects can be reused and passed around as much as you wish to avoid field duplication.

        type Entry struct {
            Logger *Logger
        
            // Contains all the fields set by the user.
            Data Fields
        
            // Time at which the log entry was created
            Time time.Time
        
            // Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic
            // This field will be set on entry firing and the value will be equal to the one in Logger struct field.
            Level Level
        
            // Calling method, with package name
            Caller *runtime.Frame
        
            // Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic
            Message string
        
            // When formatter is called in entry.log(), a Buffer may be set to entry
            Buffer *bytes.Buffer
        
            // Contains the context set by the user. Useful for hook processing etc.
            Context context.Context
            // contains filtered or unexported fields
        }
        

        func NewEntry

        func NewEntry(logger *Logger) *Entry

        func WithContext

        func WithContext(ctx context.Context) *Entry

        WithContext creates an entry from the standard logger and adds a context to it.

        func WithError

        func WithError(err error) *Entry

        WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.

        func WithField

        func WithField(key string, value interface{}) *Entry

        WithField creates an entry from the standard logger and adds a field to it. If you want multiple fields, use `WithFields`.

        Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal or Panic on the Entry it returns.

        func WithFields

        func WithFields(fields Fields) *Entry

        WithFields creates an entry from the standard logger and adds multiple fields to it. This is simply a helper for `WithField`, invoking it once for each field.

        Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal or Panic on the Entry it returns.

        func WithTime

        func WithTime(t time.Time) *Entry

        WithTime creates an entry from the standard logger and overrides the time of logs generated with it.

        Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal or Panic on the Entry it returns.

        func (*Entry) Bytes

        func (entry *Entry) Bytes() ([]byte, error)

        Returns the bytes representation of this entry from the formatter.

        func (*Entry) Debug

        func (entry *Entry) Debug(args ...interface{})

        func (*Entry) Debugf

        func (entry *Entry) Debugf(format string, args ...interface{})

        func (*Entry) Debugln

        func (entry *Entry) Debugln(args ...interface{})

        func (*Entry) Dup

        func (entry *Entry) Dup() *Entry

        func (*Entry) Error

        func (entry *Entry) Error(args ...interface{})

        func (*Entry) Errorf

        func (entry *Entry) Errorf(format string, args ...interface{})

        func (*Entry) Errorln

        func (entry *Entry) Errorln(args ...interface{})

        func (*Entry) Fatal

        func (entry *Entry) Fatal(args ...interface{})

        func (*Entry) Fatalf

        func (entry *Entry) Fatalf(format string, args ...interface{})

        func (*Entry) Fatalln

        func (entry *Entry) Fatalln(args ...interface{})

        func (Entry) HasCaller

        func (entry Entry) HasCaller() (has bool)

        func (*Entry) Info

        func (entry *Entry) Info(args ...interface{})

        func (*Entry) Infof

        func (entry *Entry) Infof(format string, args ...interface{})

        func (*Entry) Infoln

        func (entry *Entry) Infoln(args ...interface{})

        func (*Entry) Log

        func (entry *Entry) Log(level Level, args ...interface{})

        Log will log a message at the level given as parameter. Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit. For this behaviour Entry.Panic or Entry.Fatal should be used instead.

        func (*Entry) Logf

        func (entry *Entry) Logf(level Level, format string, args ...interface{})

        func (*Entry) Logln

        func (entry *Entry) Logln(level Level, args ...interface{})

        func (*Entry) Panic

        func (entry *Entry) Panic(args ...interface{})

        func (*Entry) Panicf

        func (entry *Entry) Panicf(format string, args ...interface{})

        func (*Entry) Panicln

        func (entry *Entry) Panicln(args ...interface{})

        func (*Entry) Print

        func (entry *Entry) Print(args ...interface{})

        func (*Entry) Printf

        func (entry *Entry) Printf(format string, args ...interface{})

        func (*Entry) Println

        func (entry *Entry) Println(args ...interface{})

        func (*Entry) String

        func (entry *Entry) String() (string, error)

        Returns the string representation from the reader and ultimately the formatter.

        func (*Entry) Trace

        func (entry *Entry) Trace(args ...interface{})

        func (*Entry) Tracef

        func (entry *Entry) Tracef(format string, args ...interface{})

        func (*Entry) Traceln

        func (entry *Entry) Traceln(args ...interface{})

        func (*Entry) Warn

        func (entry *Entry) Warn(args ...interface{})

        func (*Entry) Warnf

        func (entry *Entry) Warnf(format string, args ...interface{})

        func (*Entry) Warning

        func (entry *Entry) Warning(args ...interface{})

        func (*Entry) Warningf

        func (entry *Entry) Warningf(format string, args ...interface{})

        func (*Entry) Warningln

        func (entry *Entry) Warningln(args ...interface{})

        func (*Entry) Warnln

        func (entry *Entry) Warnln(args ...interface{})

        func (*Entry) WithContext

        func (entry *Entry) WithContext(ctx context.Context) *Entry

        Add a context to the Entry.

        func (*Entry) WithError

        func (entry *Entry) WithError(err error) *Entry

        Add an error as single field (using the key defined in ErrorKey) to the Entry.

        func (*Entry) WithField

        func (entry *Entry) WithField(key string, value interface{}) *Entry

        Add a single field to the Entry.

        func (*Entry) WithFields

        func (entry *Entry) WithFields(fields Fields) *Entry

        Add a map of fields to the Entry.

        func (*Entry) WithTime

        func (entry *Entry) WithTime(t time.Time) *Entry

        Overrides the time of the Entry.

        func (*Entry) Writer

        func (entry *Entry) Writer() *io.PipeWriter

        Writer returns an io.Writer that writes to the logger at the info log level

        func (*Entry) WriterLevel

        func (entry *Entry) WriterLevel(level Level) *io.PipeWriter

        WriterLevel returns an io.Writer that writes to the logger at the given log level

        type Ext1FieldLogger

        Ext1FieldLogger (the first extension to FieldLogger) is superfluous, it is here for consistancy. Do not use. Use Logger or Entry instead.

        type Ext1FieldLogger interface {
            FieldLogger
            Tracef(format string, args ...interface{})
            Trace(args ...interface{})
            Traceln(args ...interface{})
        }

        type FieldLogger

        The FieldLogger interface generalizes the Entry and Logger types

        type FieldLogger interface {
            WithField(key string, value interface{}) *Entry
            WithFields(fields Fields) *Entry
            WithError(err error) *Entry
        
            Debugf(format string, args ...interface{})
            Infof(format string, args ...interface{})
            Printf(format string, args ...interface{})
            Warnf(format string, args ...interface{})
            Warningf(format string, args ...interface{})
            Errorf(format string, args ...interface{})
            Fatalf(format string, args ...interface{})
            Panicf(format string, args ...interface{})
        
            Debug(args ...interface{})
            Info(args ...interface{})
            Print(args ...interface{})
            Warn(args ...interface{})
            Warning(args ...interface{})
            Error(args ...interface{})
            Fatal(args ...interface{})
            Panic(args ...interface{})
        
            Debugln(args ...interface{})
            Infoln(args ...interface{})
            Println(args ...interface{})
            Warnln(args ...interface{})
            Warningln(args ...interface{})
            Errorln(args ...interface{})
            Fatalln(args ...interface{})
            Panicln(args ...interface{})
        }

        type FieldMap

        FieldMap allows customization of the key names for default fields.

        type FieldMap map[fieldKey]string

        type Fields

        Fields type, used to pass to `WithFields`.

        type Fields map[string]interface{}

        type Formatter

        The Formatter interface is used to implement a custom Formatter. It takes an `Entry`. It exposes all the fields, including the default ones:

        * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. * `entry.Data["time"]`. The timestamp. * `entry.Data["level"]. The level the entry was logged at.

        Any additional fields added with `WithField` or `WithFields` are also in `entry.Data`. Format is expected to return an array of bytes which are then logged to `logger.Out`.

        type Formatter interface {
            Format(*Entry) ([]byte, error)
        }

        type Hook

        A hook to be fired when logging on the logging levels returned from `Levels()` on your implementation of the interface. Note that this is not fired in a goroutine or a channel with workers, you should handle such functionality yourself if your call is non-blocking and you don't wish for the logging calls for levels returned from `Levels()` to block.

        type Hook interface {
            Levels() []Level
            Fire(*Entry) error
        }

        type JSONFormatter

        JSONFormatter formats logs into parsable json

        type JSONFormatter struct {
            // TimestampFormat sets the format used for marshaling timestamps.
            // The format to use is the same than for time.Format or time.Parse from the standard
            // library.
            // The standard Library already provides a set of predefined format.
            TimestampFormat string
        
            // DisableTimestamp allows disabling automatic timestamps in output
            DisableTimestamp bool
        
            // DisableHTMLEscape allows disabling html escaping in output
            DisableHTMLEscape bool
        
            // DataKey allows users to put all the log entry parameters into a nested dictionary at a given key.
            DataKey string
        
            // FieldMap allows users to customize the names of keys for default fields.
            // As an example:
            // formatter := &JSONFormatter{
            //   	FieldMap: FieldMap{
            // 		 FieldKeyTime:  "@timestamp",
            // 		 FieldKeyLevel: "@level",
            // 		 FieldKeyMsg:   "@message",
            // 		 FieldKeyFunc:  "@caller",
            //    },
            // }
            FieldMap FieldMap
        
            // CallerPrettyfier can be set by the user to modify the content
            // of the function and file keys in the json data when ReportCaller is
            // activated. If any of the returned value is the empty string the
            // corresponding key will be removed from json fields.
            CallerPrettyfier func(*runtime.Frame) (function string, file string)
        
            // PrettyPrint will indent all json logs
            PrettyPrint bool
        }
        

        func (*JSONFormatter) Format

        func (f *JSONFormatter) Format(entry *Entry) ([]byte, error)

        Format renders a single log entry

        type Level

        Level type

        type Level uint32

        These are the different logging levels. You can set the logging level to log on your instance of logger, obtained with `logrus.New()`.

        const (
            // PanicLevel level, highest level of severity. Logs and then calls panic with the
            // message passed to Debug, Info, ...
            PanicLevel Level = iota
            // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
            // logging level is set to Panic.
            FatalLevel
            // ErrorLevel level. Logs. Used for errors that should definitely be noted.
            // Commonly used for hooks to send errors to an error tracking service.
            ErrorLevel
            // WarnLevel level. Non-critical entries that deserve eyes.
            WarnLevel
            // InfoLevel level. General operational entries about what's going on inside the
            // application.
            InfoLevel
            // DebugLevel level. Usually only enabled when debugging. Very verbose logging.
            DebugLevel
            // TraceLevel level. Designates finer-grained informational events than the Debug.
            TraceLevel
        )

        func GetLevel

        func GetLevel() Level

        GetLevel returns the standard logger level.

        func ParseLevel

        func ParseLevel(lvl string) (Level, error)

        ParseLevel takes a string level and returns the Logrus log level constant.

        func (Level) MarshalText

        func (level Level) MarshalText() ([]byte, error)

        func (Level) String

        func (level Level) String() string

        Convert the Level to a string. E.g. PanicLevel becomes "panic".

        func (*Level) UnmarshalText

        func (level *Level) UnmarshalText(text []byte) error

        UnmarshalText implements encoding.TextUnmarshaler.

        type LevelHooks

        Internal type for storing the hooks on a logger instance.

        type LevelHooks map[Level][]Hook

        func (LevelHooks) Add

        func (hooks LevelHooks) Add(hook Hook)

        Add a hook to an instance of logger. This is called with `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.

        func (LevelHooks) Fire

        func (hooks LevelHooks) Fire(level Level, entry *Entry) error

        Fire all the hooks for the passed level. Used by `entry.log` to fire appropriate hooks for a log entry.

        type LogFunction

        LogFunction For big messages, it can be more efficient to pass a function and only call it if the log level is actually enables rather than generating the log message and then checking if the level is enabled

        type LogFunction func() []interface{}

        type Logger

        type Logger struct {
            // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
            // file, or leave it default which is `os.Stderr`. You can also set this to
            // something more adventurous, such as logging to Kafka.
            Out io.Writer
            // Hooks for the logger instance. These allow firing events based on logging
            // levels and log entries. For example, to send errors to an error tracking
            // service, log to StatsD or dump the core on fatal errors.
            Hooks LevelHooks
            // All log entries pass through the formatter before logged to Out. The
            // included formatters are `TextFormatter` and `JSONFormatter` for which
            // TextFormatter is the default. In development (when a TTY is attached) it
            // logs with colors, but to a file it wouldn't. You can easily implement your
            // own that implements the `Formatter` interface, see the `README` or included
            // formatters for examples.
            Formatter Formatter
        
            // Flag for whether to log caller info (off by default)
            ReportCaller bool
        
            // The logging level the logger should log at. This is typically (and defaults
            // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
            // logged.
            Level Level
        
            // Function to exit the application, defaults to `os.Exit()`
            ExitFunc exitFunc
            // The buffer pool used to format the log. If it is nil, the default global
            // buffer pool will be used.
            BufferPool BufferPool
            // contains filtered or unexported fields
        }
        

        func New

        func New() *Logger

        Creates a new logger. Configuration should be set by changing `Formatter`, `Out` and `Hooks` directly on the default logger instance. You can also just instantiate your own:

        var log = &logrus.Logger{
          Out: os.Stderr,
          Formatter: new(logrus.TextFormatter),
          Hooks: make(logrus.LevelHooks),
          Level: logrus.DebugLevel,
        }
        

        It's recommended to make this a global instance called `log`.

        func StandardLogger

        func StandardLogger() *Logger

        func (*Logger) AddHook

        func (logger *Logger) AddHook(hook Hook)

        AddHook adds a hook to the logger hooks.

        func (*Logger) Debug

        func (logger *Logger) Debug(args ...interface{})

        func (*Logger) DebugFn

        func (logger *Logger) DebugFn(fn LogFunction)

        func (*Logger) Debugf

        func (logger *Logger) Debugf(format string, args ...interface{})

        func (*Logger) Debugln

        func (logger *Logger) Debugln(args ...interface{})

        func (*Logger) Error

        func (logger *Logger) Error(args ...interface{})

        func (*Logger) ErrorFn

        func (logger *Logger) ErrorFn(fn LogFunction)

        func (*Logger) Errorf

        func (logger *Logger) Errorf(format string, args ...interface{})

        func (*Logger) Errorln

        func (logger *Logger) Errorln(args ...interface{})

        func (*Logger) Exit

        func (logger *Logger) Exit(code int)

        func (*Logger) Fatal

        func (logger *Logger) Fatal(args ...interface{})

        func (*Logger) FatalFn

        func (logger *Logger) FatalFn(fn LogFunction)

        func (*Logger) Fatalf

        func (logger *Logger) Fatalf(format string, args ...interface{})

        func (*Logger) Fatalln

        func (logger *Logger) Fatalln(args ...interface{})

        func (*Logger) GetLevel

        func (logger *Logger) GetLevel() Level

        GetLevel returns the logger level.

        func (*Logger) Info

        func (logger *Logger) Info(args ...interface{})

        func (*Logger) InfoFn

        func (logger *Logger) InfoFn(fn LogFunction)

        func (*Logger) Infof

        func (logger *Logger) Infof(format string, args ...interface{})

        func (*Logger) Infoln

        func (logger *Logger) Infoln(args ...interface{})

        func (*Logger) IsLevelEnabled

        func (logger *Logger) IsLevelEnabled(level Level) bool

        IsLevelEnabled checks if the log level of the logger is greater than the level param

        func (*Logger) Log

        func (logger *Logger) Log(level Level, args ...interface{})

        Log will log a message at the level given as parameter. Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit. For this behaviour Logger.Panic or Logger.Fatal should be used instead.

        func (*Logger) LogFn

        func (logger *Logger) LogFn(level Level, fn LogFunction)

        func (*Logger) Logf

        func (logger *Logger) Logf(level Level, format string, args ...interface{})

        func (*Logger) Logln

        func (logger *Logger) Logln(level Level, args ...interface{})

        func (*Logger) Panic

        func (logger *Logger) Panic(args ...interface{})

        func (*Logger) PanicFn

        func (logger *Logger) PanicFn(fn LogFunction)

        func (*Logger) Panicf

        func (logger *Logger) Panicf(format string, args ...interface{})

        func (*Logger) Panicln

        func (logger *Logger) Panicln(args ...interface{})

        func (*Logger) Print

        func (logger *Logger) Print(args ...interface{})

        func (*Logger) PrintFn

        func (logger *Logger) PrintFn(fn LogFunction)

        func (*Logger) Printf

        func (logger *Logger) Printf(format string, args ...interface{})

        func (*Logger) Println

        func (logger *Logger) Println(args ...interface{})

        func (*Logger) ReplaceHooks

        func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks

        ReplaceHooks replaces the logger hooks and returns the old ones

        func (*Logger) SetBufferPool

        func (logger *Logger) SetBufferPool(pool BufferPool)

        SetBufferPool sets the logger buffer pool.

        func (*Logger) SetFormatter

        func (logger *Logger) SetFormatter(formatter Formatter)

        SetFormatter sets the logger formatter.

        func (*Logger) SetLevel

        func (logger *Logger) SetLevel(level Level)

        SetLevel sets the logger level.

        func (*Logger) SetNoLock

        func (logger *Logger) SetNoLock()

        When file is opened with appending mode, it's safe to write concurrently to a file (within 4k message on Linux). In these cases user can choose to disable the lock.

        func (*Logger) SetOutput

        func (logger *Logger) SetOutput(output io.Writer)

        SetOutput sets the logger output.

        func (*Logger) SetReportCaller

        func (logger *Logger) SetReportCaller(reportCaller bool)

        func (*Logger) Trace

        func (logger *Logger) Trace(args ...interface{})

        func (*Logger) TraceFn

        func (logger *Logger) TraceFn(fn LogFunction)

        func (*Logger) Tracef

        func (logger *Logger) Tracef(format string, args ...interface{})

        func (*Logger) Traceln

        func (logger *Logger) Traceln(args ...interface{})

        func (*Logger) Warn

        func (logger *Logger) Warn(args ...interface{})

        func (*Logger) WarnFn

        func (logger *Logger) WarnFn(fn LogFunction)

        func (*Logger) Warnf

        func (logger *Logger) Warnf(format string, args ...interface{})

        func (*Logger) Warning

        func (logger *Logger) Warning(args ...interface{})

        func (*Logger) WarningFn

        func (logger *Logger) WarningFn(fn LogFunction)

        func (*Logger) Warningf

        func (logger *Logger) Warningf(format string, args ...interface{})

        func (*Logger) Warningln

        func (logger *Logger) Warningln(args ...interface{})

        func (*Logger) Warnln

        func (logger *Logger) Warnln(args ...interface{})

        func (*Logger) WithContext

        func (logger *Logger) WithContext(ctx context.Context) *Entry

        Add a context to the log entry.

        func (*Logger) WithError

        func (logger *Logger) WithError(err error) *Entry

        Add an error as single field to the log entry. All it does is call `WithError` for the given `error`.

        func (*Logger) WithField

        func (logger *Logger) WithField(key string, value interface{}) *Entry

        WithField allocates a new entry and adds a field to it. Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to this new returned entry. If you want multiple fields, use `WithFields`.

        func (*Logger) WithFields

        func (logger *Logger) WithFields(fields Fields) *Entry

        Adds a struct of fields to the log entry. All it does is call `WithField` for each `Field`.

        func (*Logger) WithTime

        func (logger *Logger) WithTime(t time.Time) *Entry

        Overrides the time of the log entry.

        func (*Logger) Writer

        func (logger *Logger) Writer() *io.PipeWriter

        Writer at INFO level. See WriterLevel for details.

        Example (HttpServer)

        Code:

        logger := logrus.New()
        w := logger.Writer()
        defer w.Close()
        
        srv := http.Server{
            // create a stdlib log.Logger that writes to
            // logrus.Logger.
            ErrorLog: log.New(w, "", 0),
        }
        
        if err := srv.ListenAndServe(); err != nil {
            logger.Fatal(err)
        }
        

        Example (Stdlib)

        Code:

        logger := logrus.New()
        logger.Formatter = &logrus.JSONFormatter{}
        
        // Use logrus for standard log output
        // Note that `log` here references stdlib's log
        // Not logrus imported under the name `log`.
        log.SetOutput(logger.Writer())
        

        func (*Logger) WriterLevel

        func (logger *Logger) WriterLevel(level Level) *io.PipeWriter

        WriterLevel returns an io.Writer that can be used to write arbitrary text to the logger at the given log level. Each line written to the writer will be printed in the usual way using formatters and hooks. The writer is part of an io.Pipe and it is the callers responsibility to close the writer when done. This can be used to override the standard library logger easily.

        type MutexWrap

        type MutexWrap struct {
            // contains filtered or unexported fields
        }
        

        func (*MutexWrap) Disable

        func (mw *MutexWrap) Disable()

        func (*MutexWrap) Lock

        func (mw *MutexWrap) Lock()

        func (*MutexWrap) Unlock

        func (mw *MutexWrap) Unlock()

        type StdLogger

        StdLogger is what your logrus-enabled library should take, that way it'll accept a stdlib logger and a logrus logger. There's no standard interface, this is the closest we get, unfortunately.

        type StdLogger interface {
            Print(...interface{})
            Printf(string, ...interface{})
            Println(...interface{})
        
            Fatal(...interface{})
            Fatalf(string, ...interface{})
            Fatalln(...interface{})
        
            Panic(...interface{})
            Panicf(string, ...interface{})
            Panicln(...interface{})
        }

        type TextFormatter

        TextFormatter formats logs into text

        type TextFormatter struct {
            // Set to true to bypass checking for a TTY before outputting colors.
            ForceColors bool
        
            // Force disabling colors.
            DisableColors bool
        
            // Force quoting of all values
            ForceQuote bool
        
            // DisableQuote disables quoting for all values.
            // DisableQuote will have a lower priority than ForceQuote.
            // If both of them are set to true, quote will be forced on all values.
            DisableQuote bool
        
            // Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/
            EnvironmentOverrideColors bool
        
            // Disable timestamp logging. useful when output is redirected to logging
            // system that already adds timestamps.
            DisableTimestamp bool
        
            // Enable logging the full timestamp when a TTY is attached instead of just
            // the time passed since beginning of execution.
            FullTimestamp bool
        
            // TimestampFormat to use for display when a full timestamp is printed.
            // The format to use is the same than for time.Format or time.Parse from the standard
            // library.
            // The standard Library already provides a set of predefined format.
            TimestampFormat string
        
            // The fields are sorted by default for a consistent output. For applications
            // that log extremely frequently and don't use the JSON formatter this may not
            // be desired.
            DisableSorting bool
        
            // The keys sorting function, when uninitialized it uses sort.Strings.
            SortingFunc func([]string)
        
            // Disables the truncation of the level text to 4 characters.
            DisableLevelTruncation bool
        
            // PadLevelText Adds padding the level text so that all the levels output at the same length
            // PadLevelText is a superset of the DisableLevelTruncation option
            PadLevelText bool
        
            // QuoteEmptyFields will wrap empty fields in quotes if true
            QuoteEmptyFields bool
        
            // FieldMap allows users to customize the names of keys for default fields.
            // As an example:
            // formatter := &TextFormatter{
            //     FieldMap: FieldMap{
            //         FieldKeyTime:  "@timestamp",
            //         FieldKeyLevel: "@level",
            //         FieldKeyMsg:   "@message"}}
            FieldMap FieldMap
        
            // CallerPrettyfier can be set by the user to modify the content
            // of the function and file keys in the data when ReportCaller is
            // activated. If any of the returned value is the empty string the
            // corresponding key will be removed from fields.
            CallerPrettyfier func(*runtime.Frame) (function string, file string)
            // contains filtered or unexported fields
        }
        

        func (*TextFormatter) Format

        func (f *TextFormatter) Format(entry *Entry) ([]byte, error)

        Format renders a single log entry

        Subdirectories

        Name Synopsis
        ..
        hooks
        syslog
        test The Test package is used for testing logrus.
        writer
        src/goberkeley/berkeley/socket_zero_mq_exception.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/socket_zero_mq_exception.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  )
             6  
             7  // ErrorType enum para los diferentes tipos de errores posibles en ZeroMQ.
             8  type ErrorType int
             9  
            10  const (
            11  	// CONNECTION_ERROR Error relacionado con la conexión de ZeroMQ
            12  	CONNECTION_ERROR ErrorType = iota
            13  	// SEND_ERROR Error al enviar un mensaje a través del socket
            14  	SEND_ERROR
            15  	// RECEIVE_ERROR Error al recibir un mensaje del socket
            16  	RECEIVE_ERROR
            17  )
            18  
            19  // SocketZeroMQException estructura que encapsula un error personalizado para ZeroMQ.
            20  type SocketZeroMQException struct {
            21  	Message   string    // Mensaje de error
            22  	ErrorType ErrorType // Tipo de error
            23  }
            24  
            25  // NewSocketZeroMQException crea una nueva instancia de SocketZeroMQException.
            26  func NewSocketZeroMQException(message string, errorType ErrorType) *SocketZeroMQException {
            27  	return &SocketZeroMQException{
            28  		Message:   message,
            29  		ErrorType: errorType,
            30  	}
            31  }
            32  
            33  // Error implementación de la interfaz error para SocketZeroMQException.
            34  func (e *SocketZeroMQException) Error() string {
            35  	return fmt.Sprintf("Error: %s, Tipo de error: %v", e.Message, e.ErrorType)
            36  }
            37  
            38  // GetErrorType obtiene el tipo de error.
            39  func (e *SocketZeroMQException) GetErrorType() ErrorType {
            40  	return e.ErrorType
            41  }
            42  
        

        View as plain text

        src/goberkeley/berkeley/socket_zero_mq_exception.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/socket_zero_mq_exception.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  )
             6  
             7  // ErrorType enum para los diferentes tipos de errores posibles en ZeroMQ.
             8  type ErrorType int
             9  
            10  const (
            11  	// CONNECTION_ERROR Error relacionado con la conexión de ZeroMQ
            12  	CONNECTION_ERROR ErrorType = iota
            13  	// SEND_ERROR Error al enviar un mensaje a través del socket
            14  	SEND_ERROR
            15  	// RECEIVE_ERROR Error al recibir un mensaje del socket
            16  	RECEIVE_ERROR
            17  )
            18  
            19  // SocketZeroMQException estructura que encapsula un error personalizado para ZeroMQ.
            20  type SocketZeroMQException struct {
            21  	Message   string    // Mensaje de error
            22  	ErrorType ErrorType // Tipo de error
            23  }
            24  
            25  // NewSocketZeroMQException crea una nueva instancia de SocketZeroMQException.
            26  func NewSocketZeroMQException(message string, errorType ErrorType) *SocketZeroMQException {
            27  	return &SocketZeroMQException{
            28  		Message:   message,
            29  		ErrorType: errorType,
            30  	}
            31  }
            32  
            33  // Error implementación de la interfaz error para SocketZeroMQException.
            34  func (e *SocketZeroMQException) Error() string {
            35  	return fmt.Sprintf("Error: %s, Tipo de error: %v", e.Message, e.ErrorType)
            36  }
            37  
            38  // GetErrorType obtiene el tipo de error.
            39  func (e *SocketZeroMQException) GetErrorType() ErrorType {
            40  	return e.ErrorType
            41  }
            42  
        

        View as plain text

        src/goberkeley/berkeley/socket_zero_mq_exception.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/socket_zero_mq_exception.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  )
             6  
             7  // ErrorType enum para los diferentes tipos de errores posibles en ZeroMQ.
             8  type ErrorType int
             9  
            10  const (
            11  	// CONNECTION_ERROR Error relacionado con la conexión de ZeroMQ
            12  	CONNECTION_ERROR ErrorType = iota
            13  	// SEND_ERROR Error al enviar un mensaje a través del socket
            14  	SEND_ERROR
            15  	// RECEIVE_ERROR Error al recibir un mensaje del socket
            16  	RECEIVE_ERROR
            17  )
            18  
            19  // SocketZeroMQException estructura que encapsula un error personalizado para ZeroMQ.
            20  type SocketZeroMQException struct {
            21  	Message   string    // Mensaje de error
            22  	ErrorType ErrorType // Tipo de error
            23  }
            24  
            25  // NewSocketZeroMQException crea una nueva instancia de SocketZeroMQException.
            26  func NewSocketZeroMQException(message string, errorType ErrorType) *SocketZeroMQException {
            27  	return &SocketZeroMQException{
            28  		Message:   message,
            29  		ErrorType: errorType,
            30  	}
            31  }
            32  
            33  // Error implementación de la interfaz error para SocketZeroMQException.
            34  func (e *SocketZeroMQException) Error() string {
            35  	return fmt.Sprintf("Error: %s, Tipo de error: %v", e.Message, e.ErrorType)
            36  }
            37  
            38  // GetErrorType obtiene el tipo de error.
            39  func (e *SocketZeroMQException) GetErrorType() ErrorType {
            40  	return e.ErrorType
            41  }
            42  
        

        View as plain text

        src/goberkeley/berkeley/socket_zero_mq_exception.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/socket_zero_mq_exception.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"fmt"
             5  )
             6  
             7  // ErrorType enum para los diferentes tipos de errores posibles en ZeroMQ.
             8  type ErrorType int
             9  
            10  const (
            11  	// CONNECTION_ERROR Error relacionado con la conexión de ZeroMQ
            12  	CONNECTION_ERROR ErrorType = iota
            13  	// SEND_ERROR Error al enviar un mensaje a través del socket
            14  	SEND_ERROR
            15  	// RECEIVE_ERROR Error al recibir un mensaje del socket
            16  	RECEIVE_ERROR
            17  )
            18  
            19  // SocketZeroMQException estructura que encapsula un error personalizado para ZeroMQ.
            20  type SocketZeroMQException struct {
            21  	Message   string    // Mensaje de error
            22  	ErrorType ErrorType // Tipo de error
            23  }
            24  
            25  // NewSocketZeroMQException crea una nueva instancia de SocketZeroMQException.
            26  func NewSocketZeroMQException(message string, errorType ErrorType) *SocketZeroMQException {
            27  	return &SocketZeroMQException{
            28  		Message:   message,
            29  		ErrorType: errorType,
            30  	}
            31  }
            32  
            33  // Error implementación de la interfaz error para SocketZeroMQException.
            34  func (e *SocketZeroMQException) Error() string {
            35  	return fmt.Sprintf("Error: %s, Tipo de error: %v", e.Message, e.ErrorType)
            36  }
            37  
            38  // GetErrorType obtiene el tipo de error.
            39  func (e *SocketZeroMQException) GetErrorType() ErrorType {
            40  	return e.ErrorType
            41  }
            42  
        

        View as plain text

        src/goberkeley/berkeley/leader.go - Go Documentation Server
        ...

        Source file src/goberkeley/berkeley/leader.go

        Documentation: goberkeley/berkeley

             1  package berkeley
             2  
             3  import (
             4  	"encoding/json"
             5  	"fmt"
             6  
             7  	"log"
             8  	"strconv"
             9  	"sync"
            10  	"time"
            11  )
            12  
            13  // Mensaje JSON que se envía al seguidor.
            14  type TimeRequest struct {
            15  	Message    string `json:"message"`
            16  	Operation  string `json:"operation"`
            17  	Time       int64  `json:"time"`
            18  	LeaderAddr string `json:"leader_address"`
            19  }
            20  type DeltaRequest struct {
            21  	Message    string `json:"message"`
            22  	Operation  string `json:"operation"`
            23  	Delta      int64  `json:"delta"`
            24  	LeaderAddr string `json:"leader_address"`
            25  }
            26  type closeRequest struct {
            27  	Message    string `json:"message"`
            28  	Operation  string `json:"operation"`
            29  	LeaderAddr string `json:"leader_address"`
            30  }
            31  
            32  // Leader representa el nodo líder en el sistema Berkeley.
            33  type Leader struct {
            34  	aAbstractNode          *AbstractNode
            35  	UnreachableFollowers   map[string]*FollowerInfo
            36  	SuccessfulFollowers    map[string]*FollowerInfo
            37  	NonRespondingFollowers map[string]*FollowerInfo
            38  	TimeUpdatedFollowers   map[string]*FollowerInfo
            39  	FailedFollowers        map[string]*FollowerInfo
            40  	//mu                     sync.Mutex // Mutex para proteger los mapas en accesos concurrentes
            41  	Logger *log.Logger
            42  }
            43  
            44  // HandleProcess implements Handler.
            45  func (l *Leader) HandleProcess(message string) (string, error) {
            46  	panic("unimplemented")
            47  }
            48  
            49  // InitializeLeaderNode crea e inicializa un nuevo nodo líder.
            50  func InitializeLeaderNode(name, address string, timeout time.Duration, nodeAddresses map[string]string) (*Leader, error) {
            51  	// Suponiendo que InitializeNodeWithAddresses crea un nodo base y devuelve un puntero a AbstractNode
            52  	baseNode, err := InitializeNodeWithAddresses(name, address, timeout, nodeAddresses)
            53  	if err != nil {
            54  		return nil, err
            55  	}
            56  
            57  	// Inicializamos el líder, asignando el nodo base y un logger
            58  	leader := &Leader{
            59  		aAbstractNode: baseNode, // Asignamos el puntero a AbstractNode
            60  		Logger:        log.Default(),
            61  	}
            62  	leader.aAbstractNode.Handler = leader
            63  
            64  	return leader, nil
            65  }
            66  func (l *Leader) initStructs() {
            67  	if l.UnreachableFollowers == nil {
            68  		l.UnreachableFollowers = make(map[string]*FollowerInfo)
            69  	}
            70  	if l.SuccessfulFollowers == nil {
            71  		l.SuccessfulFollowers = make(map[string]*FollowerInfo)
            72  	}
            73  	if l.NonRespondingFollowers == nil {
            74  		l.NonRespondingFollowers = make(map[string]*FollowerInfo)
            75  	}
            76  	if l.TimeUpdatedFollowers == nil {
            77  		l.TimeUpdatedFollowers = make(map[string]*FollowerInfo)
            78  	}
            79  	if l.FailedFollowers == nil {
            80  		l.FailedFollowers = make(map[string]*FollowerInfo)
            81  	}
            82  }
            83  
            84  // StartAlgorithm implementa el algoritmo de sincronización Berkeley para el líder.
            85  func (l *Leader) StartAlgorithm() {
            86  	l.Logger.Println("Iniciando algoritmo de sincronización Berkeley...")
            87  	l.initStructs()
            88  	// Simula el envío de solicitudes de tiempo a los seguidores
            89  	l.processFollowers()
            90  
            91  	// Fase 2: Calcular el delta con la media de los tiempos
            92  	log.Println("** Fase 2 **: Calcular el delta con la media de los tiempos")
            93  	delta := l.calculateDeltaTimeDifference()
            94  	if delta != 0 {
            95  		// Paso 3: Actualizar relojes de los seguidores
            96  		log.Println("** Paso 3 **: Llamar a los seguidores para actualizar sus relojes")
            97  		l.callFollowersWithUpdatedTime(delta)
            98  
            99  		// Fase 4: Enviar mensaje de cierre
           100  		log.Println("** Fase 4 **: Enviar mensaje de cierre a los seguidores")
           101  		l.sendCloseMessagesToFollowers()
           102  
           103  		// Fase 5: Mostrar los resultados finales
           104  		log.Println("** Fase 5: Mostrar los resultados de la sincronización")
           105  		l.printResults()
           106  	} else {
           107  		// Se registra esta situación para comprobarlo más adelante en los logs
           108  		log.Println("El resultado del delta es cero por lo que no se envían actualizaciones a ningún seguidor.")
           109  	}
           110  }
           111  func (l *Leader) processFollowers() {
           112  	leaderTime := time.Now().UnixMilli() // T0
           113  	leaderAddr := l.aAbstractNode.Address
           114  
           115  	log.Printf("processFollowers: leaderAddr %s leaderTime %d.", leaderAddr, leaderTime)
           116  
           117  	// Lista de seguidores
           118  	followers := l.aAbstractNode.NodeAddresses
           119  
           120  	// Canal para los resultados
           121  	results := make(chan *FollowerInfo, len(followers))
           122  	var wg sync.WaitGroup
           123  
           124  	// Enviar solicitudes a los seguidores concurrentemente
           125  	for followerName, followerAddr := range followers {
           126  		wg.Add(1)
           127  		go func(name, addr string) {
           128  			defer wg.Done()
           129  			log.Printf("Enviando solicitud de tiempo a %s (%s).", name, addr)
           130  			l.sendTimeRequestToFollower(name, addr, leaderTime, leaderAddr, results)
           131  		}(followerName, followerAddr)
           132  	}
           133  
           134  	// Cerrar el canal una vez que todos los goroutines hayan terminado
           135  	go func() {
           136  		wg.Wait()
           137  		close(results)
           138  	}()
           139  
           140  	// Recoger y procesar los resultados
           141  	for res := range results {
           142  		if res.GetState() == "RESPONDED" {
           143  			// Seguidor que respondió correctamente
           144  			l.SuccessfulFollowers[res.GetName()] = res
           145  			log.Printf("Seguidor %s respondió correctamente con tiempo local: %d ms", res.GetName(), res.GetLocalTime())
           146  		} else if res.GetState() == "TIMEOUT" {
           147  			// Seguidor que no respondió a tiempo
           148  			l.NonRespondingFollowers[res.GetName()] = res
           149  			log.Printf("Seguidor %s no respondió a tiempo.", res.GetName())
           150  		} else {
           151  			// Seguidor que tuvo algún otro problema
           152  			l.FailedFollowers[res.GetName()] = res
           153  			log.Printf("Seguidor %s falló con estado: %s.", res.GetName(), res.GetState())
           154  		}
           155  	}
           156  
           157  	// Log final para indicar que el procesamiento de seguidores ha terminado
           158  	log.Printf("Proceso de seguidores completado. Respuestas procesadas: %d, Fallos: %d.", len(l.SuccessfulFollowers), len(l.NonRespondingFollowers))
           159  }
           160  func (l *Leader) sendTimeRequestToFollower(followerName, followerAddr string, leaderTime int64, leaderAddr string, results chan<- *FollowerInfo) {
           161  	// Crear el mensaje JSON
           162  	request := TimeRequest{
           163  		Message:    "Requesting time sync",
           164  		Operation:  "GET_TIME",
           165  		Time:       leaderTime, //T0
           166  		LeaderAddr: leaderAddr,
           167  	}
           168  
           169  	// Serializar el mensaje en formato JSON
           170  	requestData, err := json.Marshal(request)
           171  	if err != nil {
           172  		log.Printf("Error al serializar la solicitud a JSON: %v", err)
           173  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           174  		return
           175  	}
           176  
           177  	// Convertir el JSON a string
           178  	requestString := string(requestData)
           179  	log.Printf("Solicitud enviada a %s: %s", followerAddr, requestString)
           180  
           181  	// Enviar el mensaje al seguidor y recibir la respuesta
           182  	reply, err := l.aAbstractNode.SendMessageSync(followerAddr, requestString)
           183  	if err != nil {
           184  		log.Printf("Error al recibir respuesta de %s: %v", followerAddr, err)
           185  		followError := NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           186  		results <- followError
           187  		return
           188  	}
           189  
           190  	log.Printf("Respuesta recibida de %s: %s", followerAddr, reply)
           191  
           192  	// Deserializar la respuesta JSON
           193  	var response map[string]string
           194  	if err := json.Unmarshal([]byte(reply), &response); err != nil {
           195  		log.Printf("Error al procesar la respuesta de %s: %v", followerAddr, err)
           196  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           197  		return
           198  	}
           199  
           200  	// Calcular la diferencia de tiempo
           201  	endCommTime := time.Now().UnixMilli() // T0
           202  	timeComm := endCommTime - leaderTime
           203  	log.Printf("Tiempo de comunicación: %d ms", timeComm)
           204  
           205  	// Obtener el tiempo local del seguidor
           206  	localTimeStr, ok := response["localTime"]
           207  	if !ok {
           208  		log.Printf("No se encontró el campo 'localTime' en la respuesta de %s", followerAddr)
           209  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           210  		return
           211  	}
           212  
           213  	// Convertir el valor de localTime de string a int64
           214  	localTimeInt64, err := strconv.ParseInt(localTimeStr, 10, 64)
           215  	if err != nil {
           216  		log.Printf("Error al convertir 'localTime' a int64 de %s: %v", followerAddr, err)
           217  		results <- NewFollowerInfo(followerAddr, followerName, 0, 0, 0)
           218  		return
           219  	}
           220  
           221  	// Enviar los resultados al canal
           222  	log.Printf("Tiempo local recibido de %s: %d", followerAddr, localTimeInt64)
           223  	foll := NewFollowerInfo(followerAddr, followerName, localTimeInt64, timeComm, 0)
           224  	foll.SetState(Responded)
           225  	results <- foll
           226  }
           227  
           228  // calculateDeltaTimeDifference calcula la diferencia de tiempo (delta) entre el tiempo local y los tiempos de los seguidores válidos.
           229  func (l *Leader) calculateDeltaTimeDifference() int64 {
           230  	// Log de inicio de la operación de cálculo de la diferencia de tiempo
           231  	log.Println("Calculando la diferencia de tiempo (delta)")
           232  
           233  	// Obtener el tiempo actual del líder
           234  	now := time.Now().UnixMilli()
           235  	var sumTime int64 = 0           // Suma de los tiempos ajustados de los seguidores
           236  	var validFollowersCount int = 0 // Contador de seguidores con respuestas válidas
           237  
           238  	// Recorrer los seguidores exitosos y calcular la diferencia de tiempo para cada uno
           239  	for _, follower := range l.SuccessfulFollowers {
           240  		if follower.DiffTime != int64(^uint64(0)>>1) { // Verificar si el seguidor tiene un tiempo válido (Long.MAX_VALUE en Java)
           241  			followerTime := now + follower.DiffTime // Calcular el tiempo ajustado del seguidor
           242  			sumTime += followerTime                 // Sumar el tiempo ajustado
           243  			validFollowersCount++                   // Incrementar el contador de seguidores válidos
           244  		}
           245  	}
           246  
           247  	// Si se tienen seguidores válidos, calcular la diferencia de tiempo promedio
           248  	if validFollowersCount > 0 {
           249  		newNow := sumTime / int64(validFollowersCount) // Calcular el promedio de los tiempos de los seguidores
           250  		delta := newNow - now                          // Calcular la diferencia de tiempo (delta)
           251  
           252  		// Log de los resultados calculados
           253  		log.Printf("Nuevo tiempo calculado (new_now): %d\n", newNow)
           254  		log.Printf("Diferencia global (δ): %d\n", delta)
           255  
           256  		// Retornar la diferencia de tiempo (delta)
           257  		return delta
           258  	} else {
           259  		// Si no hay seguidores válidos, registrar advertencia y retornar 0
           260  		log.Println("No se han recibido respuestas válidas de los seguidores.")
           261  		return 0
           262  	}
           263  }
           264  
           265  func (l *Leader) callFollowersWithUpdatedTime(delta int64) error {
           266  	log.Printf("Enviando actualización de tiempo a los seguidores con delta: %d", delta)
           267  
           268  	// Crear un canal para gestionar las tareas concurrentes
           269  	ch := make(chan *FollowerInfo, len(l.SuccessfulFollowers))
           270  
           271  	// Usamos un WaitGroup para esperar que todas las goroutines terminen
           272  	var wg sync.WaitGroup
           273  
           274  	// Enviar las tareas en paralelo para cada seguidor
           275  	for _, follower := range l.SuccessfulFollowers {
           276  		wg.Add(1) // Incrementamos el contador del WaitGroup
           277  		go func(follower FollowerInfo) {
           278  			defer wg.Done() // Decrementamos el contador del WaitGroup cuando la goroutine termina
           279  			followerInfo := l.sendTimeUpdateToFollower(follower, delta)
           280  			ch <- followerInfo
           281  		}(*follower)
           282  	}
           283  
           284  	// Iniciar una goroutine para cerrar el canal una vez que todas las goroutines hayan terminado
           285  	go func() {
           286  		wg.Wait() // Esperamos a que todas las goroutines terminen
           287  		close(ch) // Cerramos el canal después de que todas las goroutines hayan enviado sus respuestas
           288  	}()
           289  
           290  	// Procesar las respuestas conforme vayan llegando
           291  	for followerInfo := range ch {
           292  		if followerInfo.State == "TIME_UPDATED" {
           293  			log.Printf("El seguidor %s respondió correctamente al cambio del timer.", followerInfo.Name)
           294  			l.TimeUpdatedFollowers[followerInfo.Name] = followerInfo
           295  		} else {
           296  			log.Printf("El seguidor %s no respondió al cambio de su timer.", followerInfo.Name)
           297  			l.FailedFollowers[followerInfo.Name] = followerInfo
           298  		}
           299  	}
           300  
           301  	return nil
           302  }
           303  
           304  func (l *Leader) sendTimeUpdateToFollower(follower FollowerInfo, delta int64) *FollowerInfo {
           305  
           306  	// Crear el mapa con la solicitud
           307  	request := DeltaRequest{
           308  		Message:    "Modifica el tiempo del sistema de tu servidor con el diferencial.",
           309  		Operation:  "UPDATE_TIME",
           310  		Delta:      delta,
           311  		LeaderAddr: l.aAbstractNode.Address,
           312  	}
           313  
           314  	// Serializar la solicitud a JSON
           315  	jsonRequest, err := json.Marshal(request)
           316  	if err != nil {
           317  		log.Printf("Error al serializar la solicitud para el seguidor %s: %v", follower.Name, err)
           318  		follower.State = TimeErrorSentUpdate
           319  		return &follower
           320  	}
           321  
           322  	requestString := string(jsonRequest)
           323  	log.Printf("Solicitud enviada a %s: %s", follower.GetAddress(), requestString)
           324  	// Enviar la solicitud
           325  	reply, err := l.aAbstractNode.SendMessageSync(follower.GetAddress(), requestString)
           326  	if err != nil {
           327  		log.Printf("Error al recibir respuesta de %s: %v", follower.GetAddress(), err)
           328  		followError := NewFollowerInfo(follower.GetAddress(), follower.GetName(), 0, 0, 0)
           329  		followError.State = TimeErrorSentUpdate
           330  		return followError
           331  	}
           332  
           333  	var response map[string]string
           334  	err = json.Unmarshal([]byte(reply), &response)
           335  	if err != nil {
           336  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", follower.Name, err)
           337  		follower.State = TimeErrorSentUpdate
           338  		return &follower
           339  	}
           340  
           341  	// Registrar la respuesta
           342  	followerName := response["followerName"]
           343  	operation := response["operation"]
           344  	log.Printf("Respuesta de %s: Operación %s exitosa", followerName, operation)
           345  
           346  	follower.State = TimeUpdated
           347  	return &follower
           348  }
           349  func (l *Leader) sendCloseMessagesToFollowers() {
           350  	// Crear un WaitGroup para esperar a que todas las goroutines terminen
           351  	var wg sync.WaitGroup
           352  
           353  	// Canal para recibir los resultados de las goroutines
           354  	resultCh := make(chan string, len(l.TimeUpdatedFollowers))
           355  
           356  	// Enviar mensaje de cierre a cada seguidor de manera concurrente
           357  	for _, follower := range l.TimeUpdatedFollowers {
           358  		wg.Add(1)
           359  		go func(follower FollowerInfo) {
           360  			defer wg.Done()
           361  
           362  			// Enviar el mensaje de cierre
           363  			err := l.sendCloseMessage(follower.Address, follower.Name)
           364  			if err != nil {
           365  				resultCh <- fmt.Sprintf("Error al enviar mensaje de cierre a %s: %s", follower.Name, err)
           366  				return
           367  			}
           368  
           369  			// Simulamos que el mensaje fue enviado exitosamente
           370  			resultCh <- fmt.Sprintf("Mensaje de cierre enviado con éxito a %s", follower.Name)
           371  		}(*follower)
           372  	}
           373  
           374  	// Esperar a que todas las goroutines terminen
           375  	go func() {
           376  		wg.Wait()
           377  		close(resultCh)
           378  	}()
           379  
           380  	// Procesar los resultados a medida que vayan llegando
           381  	for result := range resultCh {
           382  		log.Println(result)
           383  	}
           384  
           385  }
           386  
           387  // SendCloseMessage envía un mensaje de cierre a un seguidor.
           388  // Simulación de la función para enviar mensaje de cierre a un seguidor
           389  func (l *Leader) sendCloseMessage(followerAddress, followerName string) *FollowerInfo {
           390  	log.Printf("Enviando mensaje de cierre a %s...", followerAddress)
           391  
           392  	request := closeRequest{
           393  		Message:    "Cerrar conexión",
           394  		Operation:  "CLOSE",
           395  		LeaderAddr: l.aAbstractNode.Address,
           396  	}
           397  
           398  	// Convertir el mensaje a JSON
           399  	jsonRequest, err := json.Marshal(request)
           400  	if err != nil {
           401  		log.Printf("error al crear mensaje de cierre: %w", err)
           402  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           403  		followError.State = ErrorClose
           404  		return followError
           405  	}
           406  
           407  	// Simulamos el envío del mensaje al seguidor (usando un canal)
           408  	log.Printf("Mensaje de cierre enviado a %s: %s", followerAddress, jsonRequest)
           409  	// Serializar la solicitud a JSON
           410  
           411  	requestString := string(jsonRequest)
           412  	log.Printf("Solicitud enviada a %s: %s", followerAddress, requestString)
           413  	// Enviar la solicitud
           414  	reply, err := l.aAbstractNode.SendMessageSync(followerAddress, requestString)
           415  	if err != nil {
           416  		log.Printf("Error al recibir respuesta de %s: %v", followerAddress, err)
           417  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           418  		followError.State = ErrorClose
           419  		return followError
           420  	}
           421  
           422  	var response map[string]string
           423  	err = json.Unmarshal([]byte(reply), &response)
           424  	if err != nil {
           425  		log.Printf("Error al deserializar la respuesta del seguidor %s: %v", followerName, err)
           426  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           427  		followError.State = ErrorClose
           428  		return followError
           429  	}
           430  	// Simulamos una respuesta (en un caso real recibirías la respuesta desde el socket)
           431  	// Aquí se simula un éxito.
           432  	response = map[string]string{
           433  		"followerName": followerAddress,
           434  		"operation":    "CLOSE",
           435  	}
           436  
           437  	// Convertimos la respuesta a JSON
           438  	jsonResponse, err := json.Marshal(response)
           439  	if err != nil {
           440  		log.Printf("error al procesar la respuesta: %w", err)
           441  		followError := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           442  		followError.State = ErrorClose
           443  		return followError
           444  	}
           445  
           446  	// Simulamos la recepción de la respuesta (en un caso real, recibirías el mensaje desde el socket)
           447  	log.Printf("Respuesta recibida de %s: %s", followerAddress, jsonResponse)
           448  	follow := NewFollowerInfo(followerAddress, followerName, 0, 0, 0)
           449  	follow.State = OkClose
           450  	return follow
           451  }
           452  
           453  // PrintResults muestra los resultados del algoritmo.
           454  func (l *Leader) printResults() {
           455  	l.Logger.Println("Resultados del algoritmo Berkeley:")
           456  
           457  	// Mostrar seguidores inalcanzables
           458  	l.Logger.Println("Seguidores inalcanzables:")
           459  	for key, value := range l.UnreachableFollowers {
           460  		l.Logger.Printf("- %s: %v", key, value)
           461  	}
           462  
           463  	// Mostrar seguidores que no respondieron a tiempo
           464  	l.Logger.Println("Seguidores que no respondieron a tiempo:")
           465  	for key, value := range l.NonRespondingFollowers {
           466  		l.Logger.Printf("- %s: %v", key, value)
           467  	}
           468  
           469  	// Mostrar seguidores que respondieron correctamente
           470  	l.Logger.Println("Seguidores que respondieron correctamente:")
           471  	for key, value := range l.SuccessfulFollowers {
           472  		l.Logger.Printf("- %s: %v", key, value)
           473  	}
           474  
           475  	// Mostrar seguidores que actualizaron su tiempo correctamente
           476  	l.Logger.Println("Seguidores que actualizaron su tiempo correctamente:")
           477  	for key, value := range l.TimeUpdatedFollowers {
           478  		l.Logger.Printf("- %s: %v", key, value)
           479  	}
           480  
           481  	// Mostrar seguidores que no pudieron actualizar su tiempo
           482  	l.Logger.Println("Seguidores que no pudieron actualizar su tiempo:")
           483  	for key, value := range l.FailedFollowers {
           484  		l.Logger.Printf("- %s: %v", key, value)
           485  	}
           486  }
           487  func (l *Leader) Close() {
           488  	l.aAbstractNode.Close()
           489  }
           490  
        

        View as plain text

        PNG  IHDRSx)iCCPICC profile(c``$PPTR~  |@TTd` 24 Hbd K 1@HR6]bg9- L<% E% )I % yEE%)@P;@%D=13O@"|b\ZTJDz G0302`$40s$B7,,,XX[YYMcξC g".G-ܚ xx N/ÿX@G`T½"*"{EEM7"Q!)'yL*_ZZL->y? [ *U)P5QvPK#TSII:Vzz,05157e6}iv| Vuֹ6qvƎ:NjJ. n Ꞻ^&6>~  2)B.**""ff잸 lIa )kRosdXdff;˞g_Q]vIV骲7%Ujk?lki>*V~Stj_c݉6fO;5~3g}0|K,n]mY{+CV^vz 6l޲dV;vsv_s<~L֧ΝI>ڗ^I6ީ|übO?|!.|hd : 4o pHYs  tIME   CuBIDAThޥZyTTg9==ӓtLM=LLv4}pCQl%qKDQ#( ^@U@QTUEm}7+ s8}'#@;AD  H&L((2JK}eҵ |O 33 qd?nIDl_o )'eV.g˳3x!0lu.Ef`1(%+M)> sc2? "PE\X^}VπƋ _<>퉞r9]<1~;܊VF1r ZX{vx0[37] Fޞ Tz̹,xySӎުrXM.F$`yv<"`M?^/ toucFo2y&TVjSļ%ȱk1&DD`0Ǟh1@(=D8P҇[xy&x!zqΛec;ըQ=,wi1(wRXKsadbЃ =˨&}'eI β=Vq(zw=3w:?}/>?To0܁Y:V?WV4a[uF %ްB~߹VSXWݠ K]U;8ie@ >vtҴ S[TzS]}#ueV' lk.=3(|sFUUo6wvhU) NH'.N;vQ~i5J봘z^!ɋTKsX1V>/,esZ;lV4(v^1: \(jO-,,ΝkAnRբћ6lq9ͱg:8& Y7Fwn~'Cc>xhk̉ZMZVktv,.b}^o%G2<9{wɣWG-3CR٪MVZL]s6wyYȂVa7ܝazB~_fi%1$.=Jh;6e1t n@G2)R۔3gy߾G՗FNVoӖ+Mjn;ZCÚbS 1w{os_).ȘZ^~JݦIwĜQÔk2xٟ?&511vZ|_9ki.1Wڪ0Zm!cm ߿vѬsf ysg#&4[_W'p]sݦ3th+6㺼ٰYgkW'Nd©Oiq3%?xqLv85sʼxǤ cn!fj>-tǰe^nB韖U:҅逈w:[uK~hԳfWFo̓C:~]=WQ:-<>/d8 1w"Qd>cq]Lž~ס)/?8y딅-;۸/ֶ`MEᶩ̰dkGowlFJ'8ﲉ&e-oJjIhYg+'gֻ Y;z3uͲ;o.}i cy{qۈQQ'+OwN F#. 굷8?-|/\{6;}ׁ C({.oy· kԿ$81_^ JI^OiWQDpkho;_Y/h8)&"bkz:}.,SZ"d[I91촯?yCIDDiso['|AwIxQP"tW|X/xwM#'$q%` @(u&H$PŢrPUN<' ];'. aߛh蕻`;,_0(a~!fs)[,}w3߬f,Q3i 3 _eݲ''[0 NLj]$Df@ƣ%ZD쁯+QF2 WU_uGvkD=(=qܽ ([@^Ifpa憭'lp&ӰgLB@,rC \;7h#'zNST v^Xlmu>Tx{̛>zp[쒋r5獵qݥLh~0nG/Kؓ3Qـ0˶+Y6l}h`z[܁Du#<ړsEc|DͨZɌY"38JcT9g 7WDDp$IqcĥZpc"% apPu (ֿi8ZJ0m1 \NTCQ Mwkϛg(zYjIL_6 2 G#VYem>;!A0e=>5ǂUss{ -{7&D{{W\;Ϛ3o 'm?G U.w}Y{fn̘#^~fC<@yKm D($TXسZe}ɋSK|G˦ Ggtu)|[Lv@WxxʔpCR{@Kp𢍤W#($9MgGIENDB` /src/archive - Go Documentation Server
        ...

        Directory /src/archive

        Name Synopsis
        ..
        tar Package tar implements access to tar archives.
        zip Package zip provides support for reading and writing ZIP archives.
        tar - Go Documentation Server
        ...

        Package tar

        import "archive/tar"
        Overview
        Index
        Examples

        Overview ▾

        Package tar implements access to tar archives.

        Tape archives (tar) are a file format for storing a sequence of files that can be read and written in a streaming manner. This package aims to cover most variations of the format, including those produced by GNU and BSD tar tools.

        Example (Minimal)

        Code:

        // Create and add some files to the archive.
        var buf bytes.Buffer
        tw := tar.NewWriter(&buf)
        var files = []struct {
            Name, Body string
        }{
            {"readme.txt", "This archive contains some text files."},
            {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
            {"todo.txt", "Get animal handling license."},
        }
        for _, file := range files {
            hdr := &tar.Header{
                Name: file.Name,
                Mode: 0600,
                Size: int64(len(file.Body)),
            }
            if err := tw.WriteHeader(hdr); err != nil {
                log.Fatal(err)
            }
            if _, err := tw.Write([]byte(file.Body)); err != nil {
                log.Fatal(err)
            }
        }
        if err := tw.Close(); err != nil {
            log.Fatal(err)
        }
        
        // Open and iterate through the files in the archive.
        tr := tar.NewReader(&buf)
        for {
            hdr, err := tr.Next()
            if err == io.EOF {
                break // End of archive
            }
            if err != nil {
                log.Fatal(err)
            }
            fmt.Printf("Contents of %s:\n", hdr.Name)
            if _, err := io.Copy(os.Stdout, tr); err != nil {
                log.Fatal(err)
            }
            fmt.Println()
        }
        
        

        Output:

        Contents of readme.txt:
        This archive contains some text files.
        Contents of gopher.txt:
        Gopher names:
        George
        Geoffrey
        Gonzo
        Contents of todo.txt:
        Get animal handling license.
        

        Constants

        Type flags for Header.Typeflag.

        const (
            // Type '0' indicates a regular file.
            TypeReg = '0'
        
            // Deprecated: Use TypeReg instead.
            TypeRegA = '\x00'
        
            // Type '1' to '6' are header-only flags and may not have a data body.
            TypeLink    = '1' // Hard link
            TypeSymlink = '2' // Symbolic link
            TypeChar    = '3' // Character device node
            TypeBlock   = '4' // Block device node
            TypeDir     = '5' // Directory
            TypeFifo    = '6' // FIFO node
        
            // Type '7' is reserved.
            TypeCont = '7'
        
            // Type 'x' is used by the PAX format to store key-value records that
            // are only relevant to the next file.
            // This package transparently handles these types.
            TypeXHeader = 'x'
        
            // Type 'g' is used by the PAX format to store key-value records that
            // are relevant to all subsequent files.
            // This package only supports parsing and composing such headers,
            // but does not currently support persisting the global state across files.
            TypeXGlobalHeader = 'g'
        
            // Type 'S' indicates a sparse file in the GNU format.
            TypeGNUSparse = 'S'
        
            // Types 'L' and 'K' are used by the GNU format for a meta file
            // used to store the path or link name for the next file.
            // This package transparently handles these types.
            TypeGNULongName = 'L'
            TypeGNULongLink = 'K'
        )

        Variables

        var (
            ErrHeader          = errors.New("archive/tar: invalid tar header")
            ErrWriteTooLong    = errors.New("archive/tar: write too long")
            ErrFieldTooLong    = errors.New("archive/tar: header field too long")
            ErrWriteAfterClose = errors.New("archive/tar: write after close")
            ErrInsecurePath    = errors.New("archive/tar: insecure file path")
        )

        type Format

        Format represents the tar archive format.

        The original tar format was introduced in Unix V7. Since then, there have been multiple competing formats attempting to standardize or extend the V7 format to overcome its limitations. The most common formats are the USTAR, PAX, and GNU formats, each with their own advantages and limitations.

        The following table captures the capabilities of each format:

                          |  USTAR |       PAX |       GNU
        ------------------+--------+-----------+----------
        Name              |   256B | unlimited | unlimited
        Linkname          |   100B | unlimited | unlimited
        Size              | uint33 | unlimited |    uint89
        Mode              | uint21 |    uint21 |    uint57
        Uid/Gid           | uint21 | unlimited |    uint57
        Uname/Gname       |    32B | unlimited |       32B
        ModTime           | uint33 | unlimited |     int89
        AccessTime        |    n/a | unlimited |     int89
        ChangeTime        |    n/a | unlimited |     int89
        Devmajor/Devminor | uint21 |    uint21 |    uint57
        ------------------+--------+-----------+----------
        string encoding   |  ASCII |     UTF-8 |    binary
        sub-second times  |     no |       yes |        no
        sparse files      |     no |       yes |       yes
        

        The table's upper portion shows the Header fields, where each format reports the maximum number of bytes allowed for each string field and the integer type used to store each numeric field (where timestamps are stored as the number of seconds since the Unix epoch).

        The table's lower portion shows specialized features of each format, such as supported string encodings, support for sub-second timestamps, or support for sparse files.

        The Writer currently provides no support for sparse files.

        type Format int

        Constants to identify various tar formats.

        const (
        
            // FormatUnknown indicates that the format is unknown.
            FormatUnknown Format
        
            // FormatUSTAR represents the USTAR header format defined in POSIX.1-1988.
            //
            // While this format is compatible with most tar readers,
            // the format has several limitations making it unsuitable for some usages.
            // Most notably, it cannot support sparse files, files larger than 8GiB,
            // filenames larger than 256 characters, and non-ASCII filenames.
            //
            // Reference:
            //	http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_06
            FormatUSTAR
        
            // FormatPAX represents the PAX header format defined in POSIX.1-2001.
            //
            // PAX extends USTAR by writing a special file with Typeflag TypeXHeader
            // preceding the original header. This file contains a set of key-value
            // records, which are used to overcome USTAR's shortcomings, in addition to
            // providing the ability to have sub-second resolution for timestamps.
            //
            // Some newer formats add their own extensions to PAX by defining their
            // own keys and assigning certain semantic meaning to the associated values.
            // For example, sparse file support in PAX is implemented using keys
            // defined by the GNU manual (e.g., "GNU.sparse.map").
            //
            // Reference:
            //	http://pubs.opengroup.org/onlinepubs/009695399/utilities/pax.html
            FormatPAX
        
            // FormatGNU represents the GNU header format.
            //
            // The GNU header format is older than the USTAR and PAX standards and
            // is not compatible with them. The GNU format supports
            // arbitrary file sizes, filenames of arbitrary encoding and length,
            // sparse files, and other features.
            //
            // It is recommended that PAX be chosen over GNU unless the target
            // application can only parse GNU formatted archives.
            //
            // Reference:
            //	https://www.gnu.org/software/tar/manual/html_node/Standard.html
            FormatGNU
        )

        func (Format) String

        func (f Format) String() string

        A Header represents a single header in a tar archive. Some fields may not be populated.

        For forward compatibility, users that retrieve a Header from Reader.Next, mutate it in some ways, and then pass it back to Writer.WriteHeader should do so by creating a new Header and copying the fields that they are interested in preserving.

        type Header struct {
            // Typeflag is the type of header entry.
            // The zero value is automatically promoted to either TypeReg or TypeDir
            // depending on the presence of a trailing slash in Name.
            Typeflag byte
        
            Name     string // Name of file entry
            Linkname string // Target name of link (valid for TypeLink or TypeSymlink)
        
            Size  int64  // Logical file size in bytes
            Mode  int64  // Permission and mode bits
            Uid   int    // User ID of owner
            Gid   int    // Group ID of owner
            Uname string // User name of owner
            Gname string // Group name of owner
        
            // If the Format is unspecified, then Writer.WriteHeader rounds ModTime
            // to the nearest second and ignores the AccessTime and ChangeTime fields.
            //
            // To use AccessTime or ChangeTime, specify the Format as PAX or GNU.
            // To use sub-second resolution, specify the Format as PAX.
            ModTime    time.Time // Modification time
            AccessTime time.Time // Access time (requires either PAX or GNU support)
            ChangeTime time.Time // Change time (requires either PAX or GNU support)
        
            Devmajor int64 // Major device number (valid for TypeChar or TypeBlock)
            Devminor int64 // Minor device number (valid for TypeChar or TypeBlock)
        
            // Xattrs stores extended attributes as PAX records under the
            // "SCHILY.xattr." namespace.
            //
            // The following are semantically equivalent:
            //  h.Xattrs[key] = value
            //  h.PAXRecords["SCHILY.xattr."+key] = value
            //
            // When Writer.WriteHeader is called, the contents of Xattrs will take
            // precedence over those in PAXRecords.
            //
            // Deprecated: Use PAXRecords instead.
            Xattrs map[string]string
        
            // PAXRecords is a map of PAX extended header records.
            //
            // User-defined records should have keys of the following form:
            //	VENDOR.keyword
            // Where VENDOR is some namespace in all uppercase, and keyword may
            // not contain the '=' character (e.g., "GOLANG.pkg.version").
            // The key and value should be non-empty UTF-8 strings.
            //
            // When Writer.WriteHeader is called, PAX records derived from the
            // other fields in Header take precedence over PAXRecords.
            PAXRecords map[string]string
        
            // Format specifies the format of the tar header.
            //
            // This is set by Reader.Next as a best-effort guess at the format.
            // Since the Reader liberally reads some non-compliant files,
            // it is possible for this to be FormatUnknown.
            //
            // If the format is unspecified when Writer.WriteHeader is called,
            // then it uses the first format (in the order of USTAR, PAX, GNU)
            // capable of encoding this Header (see Format).
            Format Format
        }
        

        func FileInfoHeader

        func FileInfoHeader(fi fs.FileInfo, link string) (*Header, error)

        FileInfoHeader creates a partially-populated Header from fi. If fi describes a symlink, FileInfoHeader records link as the link target. If fi describes a directory, a slash is appended to the name.

        Since fs.FileInfo's Name method only returns the base name of the file it describes, it may be necessary to modify Header.Name to provide the full path name of the file.

        func (*Header) FileInfo

        func (h *Header) FileInfo() fs.FileInfo

        FileInfo returns an fs.FileInfo for the Header.

        type Reader

        Reader provides sequential access to the contents of a tar archive. Reader.Next advances to the next file in the archive (including the first), and then Reader can be treated as an io.Reader to access the file's data.

        type Reader struct {
            // contains filtered or unexported fields
        }
        

        func NewReader

        func NewReader(r io.Reader) *Reader

        NewReader creates a new Reader reading from r.

        func (*Reader) Next

        func (tr *Reader) Next() (*Header, error)

        Next advances to the next entry in the tar archive. The Header.Size determines how many bytes can be read for the next file. Any remaining data in the current file is automatically discarded. At the end of the archive, Next returns the error io.EOF.

        If Next encounters a non-local name (as defined by filepath.IsLocal) and the GODEBUG environment variable contains `tarinsecurepath=0`, Next returns the header with an ErrInsecurePath error. A future version of Go may introduce this behavior by default. Programs that want to accept non-local names can ignore the ErrInsecurePath error and use the returned header.

        func (*Reader) Read

        func (tr *Reader) Read(b []byte) (int, error)

        Read reads from the current file in the tar archive. It returns (0, io.EOF) when it reaches the end of that file, until [Next] is called to advance to the next file.

        If the current file is sparse, then the regions marked as a hole are read back as NUL-bytes.

        Calling Read on special types like TypeLink, TypeSymlink, TypeChar, TypeBlock, TypeDir, and TypeFifo returns (0, io.EOF) regardless of what the [Header.Size] claims.

        type Writer

        Writer provides sequential writing of a tar archive. Writer.WriteHeader begins a new file with the provided Header, and then Writer can be treated as an io.Writer to supply that file's data.

        type Writer struct {
            // contains filtered or unexported fields
        }
        

        func NewWriter

        func NewWriter(w io.Writer) *Writer

        NewWriter creates a new Writer writing to w.

        func (*Writer) AddFS

        func (tw *Writer) AddFS(fsys fs.FS) error

        AddFS adds the files from fs.FS to the archive. It walks the directory tree starting at the root of the filesystem adding each file to the tar archive while maintaining the directory structure.

        func (*Writer) Close

        func (tw *Writer) Close() error

        Close closes the tar archive by flushing the padding, and writing the footer. If the current file (from a prior call to Writer.WriteHeader) is not fully written, then this returns an error.

        func (*Writer) Flush

        func (tw *Writer) Flush() error

        Flush finishes writing the current file's block padding. The current file must be fully written before Flush can be called.

        This is unnecessary as the next call to Writer.WriteHeader or Writer.Close will implicitly flush out the file's padding.

        func (*Writer) Write

        func (tw *Writer) Write(b []byte) (int, error)

        Write writes to the current file in the tar archive. Write returns the error ErrWriteTooLong if more than Header.Size bytes are written after Writer.WriteHeader.

        Calling Write on special types like TypeLink, TypeSymlink, TypeChar, TypeBlock, TypeDir, and TypeFifo returns (0, ErrWriteTooLong) regardless of what the [Header.Size] claims.

        func (*Writer) WriteHeader

        func (tw *Writer) WriteHeader(hdr *Header) error

        WriteHeader writes hdr and prepares to accept the file's contents. The Header.Size determines how many bytes can be written for the next file. If the current file is not fully written, then this returns an error. This implicitly flushes any padding necessary before writing the header.

        zip - Go Documentation Server
        ...

        Package zip

        import "archive/zip"
        Overview
        Index
        Examples

        Overview ▾

        Package zip provides support for reading and writing ZIP archives.

        See the ZIP specification for details.

        This package does not support disk spanning.

        A note about ZIP64:

        To be backwards compatible the FileHeader has both 32 and 64 bit Size fields. The 64 bit fields will always contain the correct value and for normal archives both fields will be the same. For files requiring the ZIP64 format the 32 bit fields will be 0xffffffff and the 64 bit fields must be used instead.

        Index ▾

        Constants
        Variables
        func RegisterCompressor(method uint16, comp Compressor)
        func RegisterDecompressor(method uint16, dcomp Decompressor)
        type Compressor
        type Decompressor
        type File
            func (f *File) DataOffset() (offset int64, err error)
            func (f *File) Open() (io.ReadCloser, error)
            func (f *File) OpenRaw() (io.Reader, error)
        type FileHeader
            func FileInfoHeader(fi fs.FileInfo) (*FileHeader, error)
            func (h *FileHeader) FileInfo() fs.FileInfo
            func (h *FileHeader) ModTime() time.Time
            func (h *FileHeader) Mode() (mode fs.FileMode)
            func (h *FileHeader) SetModTime(t time.Time)
            func (h *FileHeader) SetMode(mode fs.FileMode)
        type ReadCloser
            func OpenReader(name string) (*ReadCloser, error)
            func (rc *ReadCloser) Close() error
        type Reader
            func NewReader(r io.ReaderAt, size int64) (*Reader, error)
            func (r *Reader) Open(name string) (fs.File, error)
            func (r *Reader) RegisterDecompressor(method uint16, dcomp Decompressor)
        type Writer
            func NewWriter(w io.Writer) *Writer
            func (w *Writer) AddFS(fsys fs.FS) error
            func (w *Writer) Close() error
            func (w *Writer) Copy(f *File) error
            func (w *Writer) Create(name string) (io.Writer, error)
            func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error)
            func (w *Writer) CreateRaw(fh *FileHeader) (io.Writer, error)
            func (w *Writer) Flush() error
            func (w *Writer) RegisterCompressor(method uint16, comp Compressor)
            func (w *Writer) SetComment(comment string) error
            func (w *Writer) SetOffset(n int64)

        Examples

        Reader
        Writer
        Writer.RegisterCompressor

        Package files

        reader.go register.go struct.go writer.go

        Constants

        Compression methods.

        const (
            Store   uint16 = 0 // no compression
            Deflate uint16 = 8 // DEFLATE compressed
        )

        Variables

        var (
            ErrFormat       = errors.New("zip: not a valid zip file")
            ErrAlgorithm    = errors.New("zip: unsupported compression algorithm")
            ErrChecksum     = errors.New("zip: checksum error")
            ErrInsecurePath = errors.New("zip: insecure file path")
        )

        func RegisterCompressor

        func RegisterCompressor(method uint16, comp Compressor)

        RegisterCompressor registers custom compressors for a specified method ID. The common methods Store and Deflate are built in.

        func RegisterDecompressor

        func RegisterDecompressor(method uint16, dcomp Decompressor)

        RegisterDecompressor allows custom decompressors for a specified method ID. The common methods Store and Deflate are built in.

        type Compressor

        A Compressor returns a new compressing writer, writing to w. The WriteCloser's Close method must be used to flush pending data to w. The Compressor itself must be safe to invoke from multiple goroutines simultaneously, but each returned writer will be used only by one goroutine at a time.

        type Compressor func(w io.Writer) (io.WriteCloser, error)

        type Decompressor

        A Decompressor returns a new decompressing reader, reading from r. The io.ReadCloser's Close method must be used to release associated resources. The Decompressor itself must be safe to invoke from multiple goroutines simultaneously, but each returned reader will be used only by one goroutine at a time.

        type Decompressor func(r io.Reader) io.ReadCloser

        type File

        A File is a single file in a ZIP archive. The file information is in the embedded FileHeader. The file content can be accessed by calling File.Open.

        type File struct {
            FileHeader
            // contains filtered or unexported fields
        }
        

        func (*File) DataOffset

        func (f *File) DataOffset() (offset int64, err error)

        DataOffset returns the offset of the file's possibly-compressed data, relative to the beginning of the zip file.

        Most callers should instead use File.Open, which transparently decompresses data and verifies checksums.

        func (*File) Open

        func (f *File) Open() (io.ReadCloser, error)

        Open returns a ReadCloser that provides access to the File's contents. Multiple files may be read concurrently.

        func (*File) OpenRaw

        func (f *File) OpenRaw() (io.Reader, error)

        OpenRaw returns a Reader that provides access to the File's contents without decompression.

        type FileHeader

        FileHeader describes a file within a ZIP file. See the ZIP specification for details.

        type FileHeader struct {
            // Name is the name of the file.
            //
            // It must be a relative path, not start with a drive letter (such as "C:"),
            // and must use forward slashes instead of back slashes. A trailing slash
            // indicates that this file is a directory and should have no data.
            Name string
        
            // Comment is any arbitrary user-defined string shorter than 64KiB.
            Comment string
        
            // NonUTF8 indicates that Name and Comment are not encoded in UTF-8.
            //
            // By specification, the only other encoding permitted should be CP-437,
            // but historically many ZIP readers interpret Name and Comment as whatever
            // the system's local character encoding happens to be.
            //
            // This flag should only be set if the user intends to encode a non-portable
            // ZIP file for a specific localized region. Otherwise, the Writer
            // automatically sets the ZIP format's UTF-8 flag for valid UTF-8 strings.
            NonUTF8 bool
        
            CreatorVersion uint16
            ReaderVersion  uint16
            Flags          uint16
        
            // Method is the compression method. If zero, Store is used.
            Method uint16
        
            // Modified is the modified time of the file.
            //
            // When reading, an extended timestamp is preferred over the legacy MS-DOS
            // date field, and the offset between the times is used as the timezone.
            // If only the MS-DOS date is present, the timezone is assumed to be UTC.
            //
            // When writing, an extended timestamp (which is timezone-agnostic) is
            // always emitted. The legacy MS-DOS date field is encoded according to the
            // location of the Modified time.
            Modified time.Time
        
            // ModifiedTime is an MS-DOS-encoded time.
            //
            // Deprecated: Use Modified instead.
            ModifiedTime uint16
        
            // ModifiedDate is an MS-DOS-encoded date.
            //
            // Deprecated: Use Modified instead.
            ModifiedDate uint16
        
            // CRC32 is the CRC32 checksum of the file content.
            CRC32 uint32
        
            // CompressedSize is the compressed size of the file in bytes.
            // If either the uncompressed or compressed size of the file
            // does not fit in 32 bits, CompressedSize is set to ^uint32(0).
            //
            // Deprecated: Use CompressedSize64 instead.
            CompressedSize uint32
        
            // UncompressedSize is the compressed size of the file in bytes.
            // If either the uncompressed or compressed size of the file
            // does not fit in 32 bits, CompressedSize is set to ^uint32(0).
            //
            // Deprecated: Use UncompressedSize64 instead.
            UncompressedSize uint32
        
            // CompressedSize64 is the compressed size of the file in bytes.
            CompressedSize64 uint64
        
            // UncompressedSize64 is the uncompressed size of the file in bytes.
            UncompressedSize64 uint64
        
            Extra         []byte
            ExternalAttrs uint32 // Meaning depends on CreatorVersion
        }
        

        func FileInfoHeader

        func FileInfoHeader(fi fs.FileInfo) (*FileHeader, error)

        FileInfoHeader creates a partially-populated FileHeader from an fs.FileInfo. Because fs.FileInfo's Name method returns only the base name of the file it describes, it may be necessary to modify the Name field of the returned header to provide the full path name of the file. If compression is desired, callers should set the FileHeader.Method field; it is unset by default.

        func (*FileHeader) FileInfo

        func (h *FileHeader) FileInfo() fs.FileInfo

        FileInfo returns an fs.FileInfo for the FileHeader.

        func (*FileHeader) ModTime

        func (h *FileHeader) ModTime() time.Time

        ModTime returns the modification time in UTC using the legacy [ModifiedDate] and [ModifiedTime] fields.

        Deprecated: Use [Modified] instead.

        func (*FileHeader) Mode

        func (h *FileHeader) Mode() (mode fs.FileMode)

        Mode returns the permission and mode bits for the FileHeader.

        func (*FileHeader) SetModTime

        func (h *FileHeader) SetModTime(t time.Time)

        SetModTime sets the [Modified], [ModifiedTime], and [ModifiedDate] fields to the given time in UTC.

        Deprecated: Use [Modified] instead.

        func (*FileHeader) SetMode

        func (h *FileHeader) SetMode(mode fs.FileMode)

        SetMode changes the permission and mode bits for the FileHeader.

        type ReadCloser

        A ReadCloser is a Reader that must be closed when no longer needed.

        type ReadCloser struct {
            Reader
            // contains filtered or unexported fields
        }
        

        func OpenReader

        func OpenReader(name string) (*ReadCloser, error)

        OpenReader will open the Zip file specified by name and return a ReadCloser.

        If any file inside the archive uses a non-local name (as defined by filepath.IsLocal) or a name containing backslashes and the GODEBUG environment variable contains `zipinsecurepath=0`, OpenReader returns the reader with an ErrInsecurePath error. A future version of Go may introduce this behavior by default. Programs that want to accept non-local names can ignore the ErrInsecurePath error and use the returned reader.

        func (*ReadCloser) Close

        func (rc *ReadCloser) Close() error

        Close closes the Zip file, rendering it unusable for I/O.

        type Reader

        A Reader serves content from a ZIP archive.

        type Reader struct {
            File    []*File
            Comment string
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        // Open a zip archive for reading.
        r, err := zip.OpenReader("testdata/readme.zip")
        if err != nil {
            log.Fatal(err)
        }
        defer r.Close()
        
        // Iterate through the files in the archive,
        // printing some of their contents.
        for _, f := range r.File {
            fmt.Printf("Contents of %s:\n", f.Name)
            rc, err := f.Open()
            if err != nil {
                log.Fatal(err)
            }
            _, err = io.CopyN(os.Stdout, rc, 68)
            if err != nil {
                log.Fatal(err)
            }
            rc.Close()
            fmt.Println()
        }
        

        Output:

        Contents of README:
        This is the source code repository for the Go programming language.
        

        func NewReader

        func NewReader(r io.ReaderAt, size int64) (*Reader, error)

        NewReader returns a new Reader reading from r, which is assumed to have the given size in bytes.

        If any file inside the archive uses a non-local name (as defined by filepath.IsLocal) or a name containing backslashes and the GODEBUG environment variable contains `zipinsecurepath=0`, NewReader returns the reader with an ErrInsecurePath error. A future version of Go may introduce this behavior by default. Programs that want to accept non-local names can ignore the ErrInsecurePath error and use the returned reader.

        func (*Reader) Open

        func (r *Reader) Open(name string) (fs.File, error)

        Open opens the named file in the ZIP archive, using the semantics of fs.FS.Open: paths are always slash separated, with no leading / or ../ elements.

        func (*Reader) RegisterDecompressor

        func (r *Reader) RegisterDecompressor(method uint16, dcomp Decompressor)

        RegisterDecompressor registers or overrides a custom decompressor for a specific method ID. If a decompressor for a given method is not found, Reader will default to looking up the decompressor at the package level.

        type Writer

        Writer implements a zip file writer.

        type Writer struct {
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        // Create a buffer to write our archive to.
        buf := new(bytes.Buffer)
        
        // Create a new zip archive.
        w := zip.NewWriter(buf)
        
        // Add some files to the archive.
        var files = []struct {
            Name, Body string
        }{
            {"readme.txt", "This archive contains some text files."},
            {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
            {"todo.txt", "Get animal handling licence.\nWrite more examples."},
        }
        for _, file := range files {
            f, err := w.Create(file.Name)
            if err != nil {
                log.Fatal(err)
            }
            _, err = f.Write([]byte(file.Body))
            if err != nil {
                log.Fatal(err)
            }
        }
        
        // Make sure to check the error on Close.
        err := w.Close()
        if err != nil {
            log.Fatal(err)
        }
        

        func NewWriter

        func NewWriter(w io.Writer) *Writer

        NewWriter returns a new Writer writing a zip file to w.

        func (*Writer) AddFS

        func (w *Writer) AddFS(fsys fs.FS) error

        AddFS adds the files from fs.FS to the archive. It walks the directory tree starting at the root of the filesystem adding each file to the zip using deflate while maintaining the directory structure.

        func (*Writer) Close

        func (w *Writer) Close() error

        Close finishes writing the zip file by writing the central directory. It does not close the underlying writer.

        func (*Writer) Copy

        func (w *Writer) Copy(f *File) error

        Copy copies the file f (obtained from a Reader) into w. It copies the raw form directly bypassing decompression, compression, and validation.

        func (*Writer) Create

        func (w *Writer) Create(name string) (io.Writer, error)

        Create adds a file to the zip file using the provided name. It returns a Writer to which the file contents should be written. The file contents will be compressed using the Deflate method. The name must be a relative path: it must not start with a drive letter (e.g. C:) or leading slash, and only forward slashes are allowed. To create a directory instead of a file, add a trailing slash to the name. The file's contents must be written to the io.Writer before the next call to Writer.Create, Writer.CreateHeader, or Writer.Close.

        func (*Writer) CreateHeader

        func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error)

        CreateHeader adds a file to the zip archive using the provided FileHeader for the file metadata. Writer takes ownership of fh and may mutate its fields. The caller must not modify fh after calling Writer.CreateHeader.

        This returns a Writer to which the file contents should be written. The file's contents must be written to the io.Writer before the next call to Writer.Create, Writer.CreateHeader, Writer.CreateRaw, or Writer.Close.

        func (*Writer) CreateRaw

        func (w *Writer) CreateRaw(fh *FileHeader) (io.Writer, error)

        CreateRaw adds a file to the zip archive using the provided FileHeader and returns a Writer to which the file contents should be written. The file's contents must be written to the io.Writer before the next call to Writer.Create, Writer.CreateHeader, Writer.CreateRaw, or Writer.Close.

        In contrast to Writer.CreateHeader, the bytes passed to Writer are not compressed.

        func (*Writer) Flush

        func (w *Writer) Flush() error

        Flush flushes any buffered data to the underlying writer. Calling Flush is not normally necessary; calling Close is sufficient.

        func (*Writer) RegisterCompressor

        func (w *Writer) RegisterCompressor(method uint16, comp Compressor)

        RegisterCompressor registers or overrides a custom compressor for a specific method ID. If a compressor for a given method is not found, Writer will default to looking up the compressor at the package level.

        Example

        Code:

        // Override the default Deflate compressor with a higher compression level.
        
        // Create a buffer to write our archive to.
        buf := new(bytes.Buffer)
        
        // Create a new zip archive.
        w := zip.NewWriter(buf)
        
        // Register a custom Deflate compressor.
        w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
            return flate.NewWriter(out, flate.BestCompression)
        })
        
        // Proceed to add files to w.
        

        func (*Writer) SetComment

        func (w *Writer) SetComment(comment string) error

        SetComment sets the end-of-central-directory comment field. It can only be called before Writer.Close.

        func (*Writer) SetOffset

        func (w *Writer) SetOffset(n int64)

        SetOffset sets the offset of the beginning of the zip data within the underlying writer. It should be used when the zip data is appended to an existing file, such as a binary executable. It must be called before any data is written.

        arena - Go Documentation Server
        ...

        Command arena

        The arena package provides the ability to allocate memory for a collection of Go values and free that space manually all at once, safely. The purpose of this functionality is to improve efficiency: manually freeing memory before a garbage collection delays that cycle. Less frequent cycles means the CPU cost of the garbage collector is incurred less frequently.

        This functionality in this package is mostly captured in the Arena type. Arenas allocate large chunks of memory for Go values, so they're likely to be inefficient for allocating only small amounts of small Go values. They're best used in bulk, on the order of MiB of memory allocated on each use.

        Note that by allowing for this limited form of manual memory allocation that use-after-free bugs are possible with regular Go values. This package limits the impact of these use-after-free bugs by preventing reuse of freed memory regions until the garbage collector is able to determine that it is safe. Typically, a use-after-free bug will result in a fault and a helpful error message, but this package reserves the right to not force a fault on freed memory. That means a valid implementation of this package is to just allocate all memory the way the runtime normally would, and in fact, it reserves the right to occasionally do so for some Go values.

        bufio - Go Documentation Server
        ...

        Package bufio

        import "bufio"
        Overview
        Index
        Examples

        Overview ▾

        Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.

        Index ▾

        Constants
        Variables
        func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error)
        func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error)
        func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error)
        func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error)
        type ReadWriter
            func NewReadWriter(r *Reader, w *Writer) *ReadWriter
        type Reader
            func NewReader(rd io.Reader) *Reader
            func NewReaderSize(rd io.Reader, size int) *Reader
            func (b *Reader) Buffered() int
            func (b *Reader) Discard(n int) (discarded int, err error)
            func (b *Reader) Peek(n int) ([]byte, error)
            func (b *Reader) Read(p []byte) (n int, err error)
            func (b *Reader) ReadByte() (byte, error)
            func (b *Reader) ReadBytes(delim byte) ([]byte, error)
            func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)
            func (b *Reader) ReadRune() (r rune, size int, err error)
            func (b *Reader) ReadSlice(delim byte) (line []byte, err error)
            func (b *Reader) ReadString(delim byte) (string, error)
            func (b *Reader) Reset(r io.Reader)
            func (b *Reader) Size() int
            func (b *Reader) UnreadByte() error
            func (b *Reader) UnreadRune() error
            func (b *Reader) WriteTo(w io.Writer) (n int64, err error)
        type Scanner
            func NewScanner(r io.Reader) *Scanner
            func (s *Scanner) Buffer(buf []byte, max int)
            func (s *Scanner) Bytes() []byte
            func (s *Scanner) Err() error
            func (s *Scanner) Scan() bool
            func (s *Scanner) Split(split SplitFunc)
            func (s *Scanner) Text() string
        type SplitFunc
        type Writer
            func NewWriter(w io.Writer) *Writer
            func NewWriterSize(w io.Writer, size int) *Writer
            func (b *Writer) Available() int
            func (b *Writer) AvailableBuffer() []byte
            func (b *Writer) Buffered() int
            func (b *Writer) Flush() error
            func (b *Writer) ReadFrom(r io.Reader) (n int64, err error)
            func (b *Writer) Reset(w io.Writer)
            func (b *Writer) Size() int
            func (b *Writer) Write(p []byte) (nn int, err error)
            func (b *Writer) WriteByte(c byte) error
            func (b *Writer) WriteRune(r rune) (size int, err error)
            func (b *Writer) WriteString(s string) (int, error)

        Package files

        bufio.go scan.go

        Constants

        const (
            // MaxScanTokenSize is the maximum size used to buffer a token
            // unless the user provides an explicit buffer with [Scanner.Buffer].
            // The actual maximum token size may be smaller as the buffer
            // may need to include, for instance, a newline.
            MaxScanTokenSize = 64 * 1024
        )

        Variables

        var (
            ErrInvalidUnreadByte = errors.New("bufio: invalid use of UnreadByte")
            ErrInvalidUnreadRune = errors.New("bufio: invalid use of UnreadRune")
            ErrBufferFull        = errors.New("bufio: buffer full")
            ErrNegativeCount     = errors.New("bufio: negative count")
        )

        Errors returned by Scanner.

        var (
            ErrTooLong         = errors.New("bufio.Scanner: token too long")
            ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
            ErrAdvanceTooFar   = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
            ErrBadReadCount    = errors.New("bufio.Scanner: Read returned impossible count")
        )

        ErrFinalToken is a special sentinel error value. It is intended to be returned by a Split function to indicate that the scanning should stop with no error. If the token being delivered with this error is not nil, the token is the last token.

        The value is useful to stop processing early or when it is necessary to deliver a final empty token (which is different from a nil token). One could achieve the same behavior with a custom error value but providing one here is tidier. See the emptyFinalToken example for a use of this value.

        var ErrFinalToken = errors.New("final token")

        func ScanBytes

        func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error)

        ScanBytes is a split function for a Scanner that returns each byte as a token.

        func ScanLines

        func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error)

        ScanLines is a split function for a Scanner that returns each line of text, stripped of any trailing end-of-line marker. The returned line may be empty. The end-of-line marker is one optional carriage return followed by one mandatory newline. In regular expression notation, it is `\r?\n`. The last non-empty line of input will be returned even if it has no newline.

        func ScanRunes

        func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error)

        ScanRunes is a split function for a Scanner that returns each UTF-8-encoded rune as a token. The sequence of runes returned is equivalent to that from a range loop over the input as a string, which means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd". Because of the Scan interface, this makes it impossible for the client to distinguish correctly encoded replacement runes from encoding errors.

        func ScanWords

        func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error)

        ScanWords is a split function for a Scanner that returns each space-separated word of text, with surrounding spaces deleted. It will never return an empty string. The definition of space is set by unicode.IsSpace.

        type ReadWriter

        ReadWriter stores pointers to a Reader and a Writer. It implements io.ReadWriter.

        type ReadWriter struct {
            *Reader
            *Writer
        }
        

        func NewReadWriter

        func NewReadWriter(r *Reader, w *Writer) *ReadWriter

        NewReadWriter allocates a new ReadWriter that dispatches to r and w.

        type Reader

        Reader implements buffering for an io.Reader object.

        type Reader struct {
            // contains filtered or unexported fields
        }
        

        func NewReader

        func NewReader(rd io.Reader) *Reader

        NewReader returns a new Reader whose buffer has the default size.

        func NewReaderSize

        func NewReaderSize(rd io.Reader, size int) *Reader

        NewReaderSize returns a new Reader whose buffer has at least the specified size. If the argument io.Reader is already a Reader with large enough size, it returns the underlying Reader.

        func (*Reader) Buffered

        func (b *Reader) Buffered() int

        Buffered returns the number of bytes that can be read from the current buffer.

        func (*Reader) Discard

        func (b *Reader) Discard(n int) (discarded int, err error)

        Discard skips the next n bytes, returning the number of bytes discarded.

        If Discard skips fewer than n bytes, it also returns an error. If 0 <= n <= b.Buffered(), Discard is guaranteed to succeed without reading from the underlying io.Reader.

        func (*Reader) Peek

        func (b *Reader) Peek(n int) ([]byte, error)

        Peek returns the next n bytes without advancing the reader. The bytes stop being valid at the next read call. If Peek returns fewer than n bytes, it also returns an error explaining why the read is short. The error is ErrBufferFull if n is larger than b's buffer size.

        Calling Peek prevents a Reader.UnreadByte or Reader.UnreadRune call from succeeding until the next read operation.

        func (*Reader) Read

        func (b *Reader) Read(p []byte) (n int, err error)

        Read reads data into p. It returns the number of bytes read into p. The bytes are taken from at most one Read on the underlying Reader, hence n may be less than len(p). To read exactly len(p) bytes, use io.ReadFull(b, p). If the underlying Reader can return a non-zero count with io.EOF, then this Read method can do so as well; see the io.Reader docs.

        func (*Reader) ReadByte

        func (b *Reader) ReadByte() (byte, error)

        ReadByte reads and returns a single byte. If no byte is available, returns an error.

        func (*Reader) ReadBytes

        func (b *Reader) ReadBytes(delim byte) ([]byte, error)

        ReadBytes reads until the first occurrence of delim in the input, returning a slice containing the data up to and including the delimiter. If ReadBytes encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadBytes returns err != nil if and only if the returned data does not end in delim. For simple uses, a Scanner may be more convenient.

        func (*Reader) ReadLine

        func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)

        ReadLine is a low-level line-reading primitive. Most callers should use Reader.ReadBytes('\n') or Reader.ReadString('\n') instead or use a Scanner.

        ReadLine tries to return a single line, not including the end-of-line bytes. If the line was too long for the buffer then isPrefix is set and the beginning of the line is returned. The rest of the line will be returned from future calls. isPrefix will be false when returning the last fragment of the line. The returned buffer is only valid until the next call to ReadLine. ReadLine either returns a non-nil line or it returns an error, never both.

        The text returned from ReadLine does not include the line end ("\r\n" or "\n"). No indication or error is given if the input ends without a final line end. Calling Reader.UnreadByte after ReadLine will always unread the last byte read (possibly a character belonging to the line end) even if that byte is not part of the line returned by ReadLine.

        func (*Reader) ReadRune

        func (b *Reader) ReadRune() (r rune, size int, err error)

        ReadRune reads a single UTF-8 encoded Unicode character and returns the rune and its size in bytes. If the encoded rune is invalid, it consumes one byte and returns unicode.ReplacementChar (U+FFFD) with a size of 1.

        func (*Reader) ReadSlice

        func (b *Reader) ReadSlice(delim byte) (line []byte, err error)

        ReadSlice reads until the first occurrence of delim in the input, returning a slice pointing at the bytes in the buffer. The bytes stop being valid at the next read. If ReadSlice encounters an error before finding a delimiter, it returns all the data in the buffer and the error itself (often io.EOF). ReadSlice fails with error ErrBufferFull if the buffer fills without a delim. Because the data returned from ReadSlice will be overwritten by the next I/O operation, most clients should use Reader.ReadBytes or ReadString instead. ReadSlice returns err != nil if and only if line does not end in delim.

        func (*Reader) ReadString

        func (b *Reader) ReadString(delim byte) (string, error)

        ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim. For simple uses, a Scanner may be more convenient.

        func (*Reader) Reset

        func (b *Reader) Reset(r io.Reader)

        Reset discards any buffered data, resets all state, and switches the buffered reader to read from r. Calling Reset on the zero value of Reader initializes the internal buffer to the default size. Calling b.Reset(b) (that is, resetting a Reader to itself) does nothing.

        func (*Reader) Size

        func (b *Reader) Size() int

        Size returns the size of the underlying buffer in bytes.

        func (*Reader) UnreadByte

        func (b *Reader) UnreadByte() error

        UnreadByte unreads the last byte. Only the most recently read byte can be unread.

        UnreadByte returns an error if the most recent method called on the Reader was not a read operation. Notably, Reader.Peek, Reader.Discard, and Reader.WriteTo are not considered read operations.

        func (*Reader) UnreadRune

        func (b *Reader) UnreadRune() error

        UnreadRune unreads the last rune. If the most recent method called on the Reader was not a Reader.ReadRune, Reader.UnreadRune returns an error. (In this regard it is stricter than Reader.UnreadByte, which will unread the last byte from any read operation.)

        func (*Reader) WriteTo

        func (b *Reader) WriteTo(w io.Writer) (n int64, err error)

        WriteTo implements io.WriterTo. This may make multiple calls to the Reader.Read method of the underlying Reader. If the underlying reader supports the Reader.WriteTo method, this calls the underlying Reader.WriteTo without buffering.

        type Scanner

        Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text. Successive calls to the Scanner.Scan method will step through the 'tokens' of a file, skipping the bytes between the tokens. The specification of a token is defined by a split function of type SplitFunc; the default split function breaks the input into lines with line termination stripped. Scanner.Split functions are defined in this package for scanning a file into lines, bytes, UTF-8-encoded runes, and space-delimited words. The client may instead provide a custom split function.

        Scanning stops unrecoverably at EOF, the first I/O error, or a token too large to fit in the Scanner.Buffer. When a scan stops, the reader may have advanced arbitrarily far past the last token. Programs that need more control over error handling or large tokens, or must run sequential scans on a reader, should use bufio.Reader instead.

        type Scanner struct {
            // contains filtered or unexported fields
        }
        

        Example (Custom)

        Use a Scanner with a custom split function (built by wrapping ScanWords) to validate 32-bit decimal input.

        Code:

        // An artificial input source.
        const input = "1234 5678 1234567901234567890"
        scanner := bufio.NewScanner(strings.NewReader(input))
        // Create a custom split function by wrapping the existing ScanWords function.
        split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
            advance, token, err = bufio.ScanWords(data, atEOF)
            if err == nil && token != nil {
                _, err = strconv.ParseInt(string(token), 10, 32)
            }
            return
        }
        // Set the split function for the scanning operation.
        scanner.Split(split)
        // Validate the input
        for scanner.Scan() {
            fmt.Printf("%s\n", scanner.Text())
        }
        
        if err := scanner.Err(); err != nil {
            fmt.Printf("Invalid input: %s", err)
        }
        

        Output:

        1234
        5678
        Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range
        

        Example (EarlyStop)

        Use a Scanner with a custom split function to parse a comma-separated list with an empty final value but stops at the token "STOP".

        Code:

        onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
            i := bytes.IndexByte(data, ',')
            if i == -1 {
                if !atEOF {
                    return 0, nil, nil
                }
                // If we have reached the end, return the last token.
                return 0, data, bufio.ErrFinalToken
            }
            // If the token is "STOP", stop the scanning and ignore the rest.
            if string(data[:i]) == "STOP" {
                return i + 1, nil, bufio.ErrFinalToken
            }
            // Otherwise, return the token before the comma.
            return i + 1, data[:i], nil
        }
        const input = "1,2,STOP,4,"
        scanner := bufio.NewScanner(strings.NewReader(input))
        scanner.Split(onComma)
        for scanner.Scan() {
            fmt.Printf("Got a token %q\n", scanner.Text())
        }
        if err := scanner.Err(); err != nil {
            fmt.Fprintln(os.Stderr, "reading input:", err)
        }
        

        Output:

        Got a token "1"
        Got a token "2"
        

        Example (EmptyFinalToken)

        Use a Scanner with a custom split function to parse a comma-separated list with an empty final value.

        Code:

        // Comma-separated list; last entry is empty.
        const input = "1,2,3,4,"
        scanner := bufio.NewScanner(strings.NewReader(input))
        // Define a split function that separates on commas.
        onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
            for i := 0; i < len(data); i++ {
                if data[i] == ',' {
                    return i + 1, data[:i], nil
                }
            }
            if !atEOF {
                return 0, nil, nil
            }
            // There is one final token to be delivered, which may be the empty string.
            // Returning bufio.ErrFinalToken here tells Scan there are no more tokens after this
            // but does not trigger an error to be returned from Scan itself.
            return 0, data, bufio.ErrFinalToken
        }
        scanner.Split(onComma)
        // Scan.
        for scanner.Scan() {
            fmt.Printf("%q ", scanner.Text())
        }
        if err := scanner.Err(); err != nil {
            fmt.Fprintln(os.Stderr, "reading input:", err)
        }
        

        Output:

        "1" "2" "3" "4" ""
        

        Example (Lines)

        The simplest use of a Scanner, to read standard input as a set of lines.

        Code:

        scanner := bufio.NewScanner(os.Stdin)
        for scanner.Scan() {
            fmt.Println(scanner.Text()) // Println will add back the final '\n'
        }
        if err := scanner.Err(); err != nil {
            fmt.Fprintln(os.Stderr, "reading standard input:", err)
        }
        

        Example (Words)

        Use a Scanner to implement a simple word-count utility by scanning the input as a sequence of space-delimited tokens.

        Code:

        // An artificial input source.
        const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
        scanner := bufio.NewScanner(strings.NewReader(input))
        // Set the split function for the scanning operation.
        scanner.Split(bufio.ScanWords)
        // Count the words.
        count := 0
        for scanner.Scan() {
            count++
        }
        if err := scanner.Err(); err != nil {
            fmt.Fprintln(os.Stderr, "reading input:", err)
        }
        fmt.Printf("%d\n", count)
        

        Output:

        15
        

        func NewScanner

        func NewScanner(r io.Reader) *Scanner

        NewScanner returns a new Scanner to read from r. The split function defaults to ScanLines.

        func (*Scanner) Buffer

        func (s *Scanner) Buffer(buf []byte, max int)

        Buffer sets the initial buffer to use when scanning and the maximum size of buffer that may be allocated during scanning. The maximum token size must be less than the larger of max and cap(buf). If max <= cap(buf), Scanner.Scan will use this buffer only and do no allocation.

        By default, Scanner.Scan uses an internal buffer and sets the maximum token size to MaxScanTokenSize.

        Buffer panics if it is called after scanning has started.

        func (*Scanner) Bytes

        func (s *Scanner) Bytes() []byte

        Bytes returns the most recent token generated by a call to Scanner.Scan. The underlying array may point to data that will be overwritten by a subsequent call to Scan. It does no allocation.

        Example

        Return the most recent call to Scan as a []byte.

        Code:

        scanner := bufio.NewScanner(strings.NewReader("gopher"))
        for scanner.Scan() {
            fmt.Println(len(scanner.Bytes()) == 6)
        }
        if err := scanner.Err(); err != nil {
            fmt.Fprintln(os.Stderr, "shouldn't see an error scanning a string")
        }
        

        Output:

        true
        

        func (*Scanner) Err

        func (s *Scanner) Err() error

        Err returns the first non-EOF error that was encountered by the Scanner.

        func (*Scanner) Scan

        func (s *Scanner) Scan() bool

        Scan advances the Scanner to the next token, which will then be available through the Scanner.Bytes or Scanner.Text method. It returns false when there are no more tokens, either by reaching the end of the input or an error. After Scan returns false, the Scanner.Err method will return any error that occurred during scanning, except that if it was io.EOF, Scanner.Err will return nil. Scan panics if the split function returns too many empty tokens without advancing the input. This is a common error mode for scanners.

        func (*Scanner) Split

        func (s *Scanner) Split(split SplitFunc)

        Split sets the split function for the Scanner. The default split function is ScanLines.

        Split panics if it is called after scanning has started.

        func (*Scanner) Text

        func (s *Scanner) Text() string

        Text returns the most recent token generated by a call to Scanner.Scan as a newly allocated string holding its bytes.

        type SplitFunc

        SplitFunc is the signature of the split function used to tokenize the input. The arguments are an initial substring of the remaining unprocessed data and a flag, atEOF, that reports whether the Reader has no more data to give. The return values are the number of bytes to advance the input and the next token to return to the user, if any, plus an error, if any.

        Scanning stops if the function returns an error, in which case some of the input may be discarded. If that error is ErrFinalToken, scanning stops with no error. A non-nil token delivered with ErrFinalToken will be the last token, and a nil token with ErrFinalToken immediately stops the scanning.

        Otherwise, the Scanner advances the input. If the token is not nil, the Scanner returns it to the user. If the token is nil, the Scanner reads more data and continues scanning; if there is no more data--if atEOF was true--the Scanner returns. If the data does not yet hold a complete token, for instance if it has no newline while scanning lines, a SplitFunc can return (0, nil, nil) to signal the Scanner to read more data into the slice and try again with a longer slice starting at the same point in the input.

        The function is never called with an empty data slice unless atEOF is true. If atEOF is true, however, data may be non-empty and, as always, holds unprocessed text.

        type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)

        type Writer

        Writer implements buffering for an io.Writer object. If an error occurs writing to a Writer, no more data will be accepted and all subsequent writes, and Writer.Flush, will return the error. After all data has been written, the client should call the Writer.Flush method to guarantee all data has been forwarded to the underlying io.Writer.

        type Writer struct {
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        w := bufio.NewWriter(os.Stdout)
        fmt.Fprint(w, "Hello, ")
        fmt.Fprint(w, "world!")
        w.Flush() // Don't forget to flush!
        

        Output:

        Hello, world!
        

        func NewWriter

        func NewWriter(w io.Writer) *Writer

        NewWriter returns a new Writer whose buffer has the default size. If the argument io.Writer is already a Writer with large enough buffer size, it returns the underlying Writer.

        func NewWriterSize

        func NewWriterSize(w io.Writer, size int) *Writer

        NewWriterSize returns a new Writer whose buffer has at least the specified size. If the argument io.Writer is already a Writer with large enough size, it returns the underlying Writer.

        func (*Writer) Available

        func (b *Writer) Available() int

        Available returns how many bytes are unused in the buffer.

        func (*Writer) AvailableBuffer

        func (b *Writer) AvailableBuffer() []byte

        AvailableBuffer returns an empty buffer with b.Available() capacity. This buffer is intended to be appended to and passed to an immediately succeeding Writer.Write call. The buffer is only valid until the next write operation on b.

        Example

        Code:

        w := bufio.NewWriter(os.Stdout)
        for _, i := range []int64{1, 2, 3, 4} {
            b := w.AvailableBuffer()
            b = strconv.AppendInt(b, i, 10)
            b = append(b, ' ')
            w.Write(b)
        }
        w.Flush()
        

        Output:

        1 2 3 4
        

        func (*Writer) Buffered

        func (b *Writer) Buffered() int

        Buffered returns the number of bytes that have been written into the current buffer.

        func (*Writer) Flush

        func (b *Writer) Flush() error

        Flush writes any buffered data to the underlying io.Writer.

        func (*Writer) ReadFrom

        func (b *Writer) ReadFrom(r io.Reader) (n int64, err error)

        ReadFrom implements io.ReaderFrom. If the underlying writer supports the ReadFrom method, this calls the underlying ReadFrom. If there is buffered data and an underlying ReadFrom, this fills the buffer and writes it before calling ReadFrom.

        func (*Writer) Reset

        func (b *Writer) Reset(w io.Writer)

        Reset discards any unflushed buffered data, clears any error, and resets b to write its output to w. Calling Reset on the zero value of Writer initializes the internal buffer to the default size. Calling w.Reset(w) (that is, resetting a Writer to itself) does nothing.

        func (*Writer) Size

        func (b *Writer) Size() int

        Size returns the size of the underlying buffer in bytes.

        func (*Writer) Write

        func (b *Writer) Write(p []byte) (nn int, err error)

        Write writes the contents of p into the buffer. It returns the number of bytes written. If nn < len(p), it also returns an error explaining why the write is short.

        func (*Writer) WriteByte

        func (b *Writer) WriteByte(c byte) error

        WriteByte writes a single byte.

        func (*Writer) WriteRune

        func (b *Writer) WriteRune(r rune) (size int, err error)

        WriteRune writes a single Unicode code point, returning the number of bytes written and any error.

        func (*Writer) WriteString

        func (b *Writer) WriteString(s string) (int, error)

        WriteString writes a string. It returns the number of bytes written. If the count is less than len(s), it also returns an error explaining why the write is short.

        bytes - Go Documentation Server
        ...

        Package bytes

        import "bytes"
        Overview
        Index
        Examples

        Overview ▾

        Package bytes implements functions for the manipulation of byte slices. It is analogous to the facilities of the strings package.

        Index ▾

        Constants
        Variables
        func Clone(b []byte) []byte
        func Compare(a, b []byte) int
        func Contains(b, subslice []byte) bool
        func ContainsAny(b []byte, chars string) bool
        func ContainsFunc(b []byte, f func(rune) bool) bool
        func ContainsRune(b []byte, r rune) bool
        func Count(s, sep []byte) int
        func Cut(s, sep []byte) (before, after []byte, found bool)
        func CutPrefix(s, prefix []byte) (after []byte, found bool)
        func CutSuffix(s, suffix []byte) (before []byte, found bool)
        func Equal(a, b []byte) bool
        func EqualFold(s, t []byte) bool
        func Fields(s []byte) [][]byte
        func FieldsFunc(s []byte, f func(rune) bool) [][]byte
        func HasPrefix(s, prefix []byte) bool
        func HasSuffix(s, suffix []byte) bool
        func Index(s, sep []byte) int
        func IndexAny(s []byte, chars string) int
        func IndexByte(b []byte, c byte) int
        func IndexFunc(s []byte, f func(r rune) bool) int
        func IndexRune(s []byte, r rune) int
        func Join(s [][]byte, sep []byte) []byte
        func LastIndex(s, sep []byte) int
        func LastIndexAny(s []byte, chars string) int
        func LastIndexByte(s []byte, c byte) int
        func LastIndexFunc(s []byte, f func(r rune) bool) int
        func Map(mapping func(r rune) rune, s []byte) []byte
        func Repeat(b []byte, count int) []byte
        func Replace(s, old, new []byte, n int) []byte
        func ReplaceAll(s, old, new []byte) []byte
        func Runes(s []byte) []rune
        func Split(s, sep []byte) [][]byte
        func SplitAfter(s, sep []byte) [][]byte
        func SplitAfterN(s, sep []byte, n int) [][]byte
        func SplitN(s, sep []byte, n int) [][]byte
        func Title(s []byte) []byte
        func ToLower(s []byte) []byte
        func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte
        func ToTitle(s []byte) []byte
        func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte
        func ToUpper(s []byte) []byte
        func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte
        func ToValidUTF8(s, replacement []byte) []byte
        func Trim(s []byte, cutset string) []byte
        func TrimFunc(s []byte, f func(r rune) bool) []byte
        func TrimLeft(s []byte, cutset string) []byte
        func TrimLeftFunc(s []byte, f func(r rune) bool) []byte
        func TrimPrefix(s, prefix []byte) []byte
        func TrimRight(s []byte, cutset string) []byte
        func TrimRightFunc(s []byte, f func(r rune) bool) []byte
        func TrimSpace(s []byte) []byte
        func TrimSuffix(s, suffix []byte) []byte
        type Buffer
            func NewBuffer(buf []byte) *Buffer
            func NewBufferString(s string) *Buffer
            func (b *Buffer) Available() int
            func (b *Buffer) AvailableBuffer() []byte
            func (b *Buffer) Bytes() []byte
            func (b *Buffer) Cap() int
            func (b *Buffer) Grow(n int)
            func (b *Buffer) Len() int
            func (b *Buffer) Next(n int) []byte
            func (b *Buffer) Read(p []byte) (n int, err error)
            func (b *Buffer) ReadByte() (byte, error)
            func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)
            func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)
            func (b *Buffer) ReadRune() (r rune, size int, err error)
            func (b *Buffer) ReadString(delim byte) (line string, err error)
            func (b *Buffer) Reset()
            func (b *Buffer) String() string
            func (b *Buffer) Truncate(n int)
            func (b *Buffer) UnreadByte() error
            func (b *Buffer) UnreadRune() error
            func (b *Buffer) Write(p []byte) (n int, err error)
            func (b *Buffer) WriteByte(c byte) error
            func (b *Buffer) WriteRune(r rune) (n int, err error)
            func (b *Buffer) WriteString(s string) (n int, err error)
            func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)
        type Reader
            func NewReader(b []byte) *Reader
            func (r *Reader) Len() int
            func (r *Reader) Read(b []byte) (n int, err error)
            func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)
            func (r *Reader) ReadByte() (byte, error)
            func (r *Reader) ReadRune() (ch rune, size int, err error)
            func (r *Reader) Reset(b []byte)
            func (r *Reader) Seek(offset int64, whence int) (int64, error)
            func (r *Reader) Size() int64
            func (r *Reader) UnreadByte() error
            func (r *Reader) UnreadRune() error
            func (r *Reader) WriteTo(w io.Writer) (n int64, err error)

        Package files

        buffer.go bytes.go reader.go

        Constants

        MinRead is the minimum slice size passed to a Read call by Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond what is required to hold the contents of r, ReadFrom will not grow the underlying buffer.

        const MinRead = 512

        Variables

        ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer.

        var ErrTooLarge = errors.New("bytes.Buffer: too large")

        func Clone

        func Clone(b []byte) []byte

        Clone returns a copy of b[:len(b)]. The result may have additional unused capacity. Clone(nil) returns nil.

        Example

        Code:

        b := []byte("abc")
        clone := bytes.Clone(b)
        fmt.Printf("%s\n", clone)
        clone[0] = 'd'
        fmt.Printf("%s\n", b)
        fmt.Printf("%s\n", clone)
        

        Output:

        abc
        abc
        dbc
        

        func Compare

        func Compare(a, b []byte) int

        Compare returns an integer comparing two byte slices lexicographically. The result will be 0 if a == b, -1 if a < b, and +1 if a > b. A nil argument is equivalent to an empty slice.

        Example

        Code:

        // Interpret Compare's result by comparing it to zero.
        var a, b []byte
        if bytes.Compare(a, b) < 0 {
            // a less b
        }
        if bytes.Compare(a, b) <= 0 {
            // a less or equal b
        }
        if bytes.Compare(a, b) > 0 {
            // a greater b
        }
        if bytes.Compare(a, b) >= 0 {
            // a greater or equal b
        }
        
        // Prefer Equal to Compare for equality comparisons.
        if bytes.Equal(a, b) {
            // a equal b
        }
        if !bytes.Equal(a, b) {
            // a not equal b
        }
        

        func Contains

        func Contains(b, subslice []byte) bool

        Contains reports whether subslice is within b.

        Example

        Code:

        fmt.Println(bytes.Contains([]byte("seafood"), []byte("foo")))
        fmt.Println(bytes.Contains([]byte("seafood"), []byte("bar")))
        fmt.Println(bytes.Contains([]byte("seafood"), []byte("")))
        fmt.Println(bytes.Contains([]byte(""), []byte("")))
        

        Output:

        true
        false
        true
        true
        

        func ContainsAny

        func ContainsAny(b []byte, chars string) bool

        ContainsAny reports whether any of the UTF-8-encoded code points in chars are within b.

        Example

        Code:

        fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "fÄo!"))
        fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "去是伟大的."))
        fmt.Println(bytes.ContainsAny([]byte("I like seafood."), ""))
        fmt.Println(bytes.ContainsAny([]byte(""), ""))
        

        Output:

        true
        true
        false
        false
        

        func ContainsFunc

        func ContainsFunc(b []byte, f func(rune) bool) bool

        ContainsFunc reports whether any of the UTF-8-encoded code points r within b satisfy f(r).

        Example

        Code:

        f := func(r rune) bool {
            return r >= 'a' && r <= 'z'
        }
        fmt.Println(bytes.ContainsFunc([]byte("HELLO"), f))
        fmt.Println(bytes.ContainsFunc([]byte("World"), f))
        

        Output:

        false
        true
        

        func ContainsRune

        func ContainsRune(b []byte, r rune) bool

        ContainsRune reports whether the rune is contained in the UTF-8-encoded byte slice b.

        Example

        Code:

        fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'f'))
        fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'ö'))
        fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '大'))
        fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '!'))
        fmt.Println(bytes.ContainsRune([]byte(""), '@'))
        

        Output:

        true
        false
        true
        true
        false
        

        func Count

        func Count(s, sep []byte) int

        Count counts the number of non-overlapping instances of sep in s. If sep is an empty slice, Count returns 1 + the number of UTF-8-encoded code points in s.

        Example

        Code:

        fmt.Println(bytes.Count([]byte("cheese"), []byte("e")))
        fmt.Println(bytes.Count([]byte("five"), []byte(""))) // before & after each rune
        

        Output:

        3
        5
        

        func Cut

        func Cut(s, sep []byte) (before, after []byte, found bool)

        Cut slices s around the first instance of sep, returning the text before and after sep. The found result reports whether sep appears in s. If sep does not appear in s, cut returns s, nil, false.

        Cut returns slices of the original slice s, not copies.

        Example

        Code:

        show := func(s, sep string) {
            before, after, found := bytes.Cut([]byte(s), []byte(sep))
            fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
        }
        show("Gopher", "Go")
        show("Gopher", "ph")
        show("Gopher", "er")
        show("Gopher", "Badger")
        

        Output:

        Cut("Gopher", "Go") = "", "pher", true
        Cut("Gopher", "ph") = "Go", "er", true
        Cut("Gopher", "er") = "Goph", "", true
        Cut("Gopher", "Badger") = "Gopher", "", false
        

        func CutPrefix

        func CutPrefix(s, prefix []byte) (after []byte, found bool)

        CutPrefix returns s without the provided leading prefix byte slice and reports whether it found the prefix. If s doesn't start with prefix, CutPrefix returns s, false. If prefix is the empty byte slice, CutPrefix returns s, true.

        CutPrefix returns slices of the original slice s, not copies.

        Example

        Code:

        show := func(s, sep string) {
            after, found := bytes.CutPrefix([]byte(s), []byte(sep))
            fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, sep, after, found)
        }
        show("Gopher", "Go")
        show("Gopher", "ph")
        

        Output:

        CutPrefix("Gopher", "Go") = "pher", true
        CutPrefix("Gopher", "ph") = "Gopher", false
        

        func CutSuffix

        func CutSuffix(s, suffix []byte) (before []byte, found bool)

        CutSuffix returns s without the provided ending suffix byte slice and reports whether it found the suffix. If s doesn't end with suffix, CutSuffix returns s, false. If suffix is the empty byte slice, CutSuffix returns s, true.

        CutSuffix returns slices of the original slice s, not copies.

        Example

        Code:

        show := func(s, sep string) {
            before, found := bytes.CutSuffix([]byte(s), []byte(sep))
            fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, sep, before, found)
        }
        show("Gopher", "Go")
        show("Gopher", "er")
        

        Output:

        CutSuffix("Gopher", "Go") = "Gopher", false
        CutSuffix("Gopher", "er") = "Goph", true
        

        func Equal

        func Equal(a, b []byte) bool

        Equal reports whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice.

        Example

        Code:

        fmt.Println(bytes.Equal([]byte("Go"), []byte("Go")))
        fmt.Println(bytes.Equal([]byte("Go"), []byte("C++")))
        

        Output:

        true
        false
        

        func EqualFold

        func EqualFold(s, t []byte) bool

        EqualFold reports whether s and t, interpreted as UTF-8 strings, are equal under simple Unicode case-folding, which is a more general form of case-insensitivity.

        Example

        Code:

        fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go")))
        

        Output:

        true
        

        func Fields

        func Fields(s []byte) [][]byte

        Fields interprets s as a sequence of UTF-8-encoded code points. It splits the slice s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of subslices of s or an empty slice if s contains only white space.

        Example

        Code:

        fmt.Printf("Fields are: %q", bytes.Fields([]byte("  foo bar  baz   ")))
        

        Output:

        Fields are: ["foo" "bar" "baz"]
        

        func FieldsFunc

        func FieldsFunc(s []byte, f func(rune) bool) [][]byte

        FieldsFunc interprets s as a sequence of UTF-8-encoded code points. It splits the slice s at each run of code points c satisfying f(c) and returns a slice of subslices of s. If all code points in s satisfy f(c), or len(s) == 0, an empty slice is returned.

        FieldsFunc makes no guarantees about the order in which it calls f(c) and assumes that f always returns the same value for a given c.

        Example

        Code:

        f := func(c rune) bool {
            return !unicode.IsLetter(c) && !unicode.IsNumber(c)
        }
        fmt.Printf("Fields are: %q", bytes.FieldsFunc([]byte("  foo1;bar2,baz3..."), f))
        

        Output:

        Fields are: ["foo1" "bar2" "baz3"]
        

        func HasPrefix

        func HasPrefix(s, prefix []byte) bool

        HasPrefix reports whether the byte slice s begins with prefix.

        Example

        Code:

        fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
        fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
        fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
        

        Output:

        true
        false
        true
        

        func HasSuffix

        func HasSuffix(s, suffix []byte) bool

        HasSuffix reports whether the byte slice s ends with suffix.

        Example

        Code:

        fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("go")))
        fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("O")))
        fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("Ami")))
        fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("")))
        

        Output:

        true
        false
        false
        true
        

        func Index

        func Index(s, sep []byte) int

        Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.

        Example

        Code:

        fmt.Println(bytes.Index([]byte("chicken"), []byte("ken")))
        fmt.Println(bytes.Index([]byte("chicken"), []byte("dmr")))
        

        Output:

        4
        -1
        

        func IndexAny

        func IndexAny(s []byte, chars string) int

        IndexAny interprets s as a sequence of UTF-8-encoded Unicode code points. It returns the byte index of the first occurrence in s of any of the Unicode code points in chars. It returns -1 if chars is empty or if there is no code point in common.

        Example

        Code:

        fmt.Println(bytes.IndexAny([]byte("chicken"), "aeiouy"))
        fmt.Println(bytes.IndexAny([]byte("crwth"), "aeiouy"))
        

        Output:

        2
        -1
        

        func IndexByte

        func IndexByte(b []byte, c byte) int

        IndexByte returns the index of the first instance of c in b, or -1 if c is not present in b.

        Example

        Code:

        fmt.Println(bytes.IndexByte([]byte("chicken"), byte('k')))
        fmt.Println(bytes.IndexByte([]byte("chicken"), byte('g')))
        

        Output:

        4
        -1
        

        func IndexFunc

        func IndexFunc(s []byte, f func(r rune) bool) int

        IndexFunc interprets s as a sequence of UTF-8-encoded code points. It returns the byte index in s of the first Unicode code point satisfying f(c), or -1 if none do.

        Example

        Code:

        f := func(c rune) bool {
            return unicode.Is(unicode.Han, c)
        }
        fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f))
        fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f))
        

        Output:

        7
        -1
        

        func IndexRune

        func IndexRune(s []byte, r rune) int

        IndexRune interprets s as a sequence of UTF-8-encoded code points. It returns the byte index of the first occurrence in s of the given rune. It returns -1 if rune is not present in s. If r is utf8.RuneError, it returns the first instance of any invalid UTF-8 byte sequence.

        Example

        Code:

        fmt.Println(bytes.IndexRune([]byte("chicken"), 'k'))
        fmt.Println(bytes.IndexRune([]byte("chicken"), 'd'))
        

        Output:

        4
        -1
        

        func Join

        func Join(s [][]byte, sep []byte) []byte

        Join concatenates the elements of s to create a new byte slice. The separator sep is placed between elements in the resulting slice.

        Example

        Code:

        s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")}
        fmt.Printf("%s", bytes.Join(s, []byte(", ")))
        

        Output:

        foo, bar, baz
        

        func LastIndex

        func LastIndex(s, sep []byte) int

        LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s.

        Example

        Code:

        fmt.Println(bytes.Index([]byte("go gopher"), []byte("go")))
        fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("go")))
        fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("rodent")))
        

        Output:

        0
        3
        -1
        

        func LastIndexAny

        func LastIndexAny(s []byte, chars string) int

        LastIndexAny interprets s as a sequence of UTF-8-encoded Unicode code points. It returns the byte index of the last occurrence in s of any of the Unicode code points in chars. It returns -1 if chars is empty or if there is no code point in common.

        Example

        Code:

        fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "MüQp"))
        fmt.Println(bytes.LastIndexAny([]byte("go 地鼠"), "地大"))
        fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "z,!."))
        

        Output:

        5
        3
        -1
        

        func LastIndexByte

        func LastIndexByte(s []byte, c byte) int

        LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s.

        Example

        Code:

        fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('g')))
        fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('r')))
        fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('z')))
        

        Output:

        3
        8
        -1
        

        func LastIndexFunc

        func LastIndexFunc(s []byte, f func(r rune) bool) int

        LastIndexFunc interprets s as a sequence of UTF-8-encoded code points. It returns the byte index in s of the last Unicode code point satisfying f(c), or -1 if none do.

        Example

        Code:

        fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsLetter))
        fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsPunct))
        fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsNumber))
        

        Output:

        8
        9
        -1
        

        func Map

        func Map(mapping func(r rune) rune, s []byte) []byte

        Map returns a copy of the byte slice s with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the byte slice with no replacement. The characters in s and the output are interpreted as UTF-8-encoded code points.

        Example

        Code:

        rot13 := func(r rune) rune {
            switch {
            case r >= 'A' && r <= 'Z':
                return 'A' + (r-'A'+13)%26
            case r >= 'a' && r <= 'z':
                return 'a' + (r-'a'+13)%26
            }
            return r
        }
        fmt.Printf("%s\n", bytes.Map(rot13, []byte("'Twas brillig and the slithy gopher...")))
        

        Output:

        'Gjnf oevyyvt naq gur fyvgul tbcure...
        

        func Repeat

        func Repeat(b []byte, count int) []byte

        Repeat returns a new byte slice consisting of count copies of b.

        It panics if count is negative or if the result of (len(b) * count) overflows.

        Example

        Code:

        fmt.Printf("ba%s", bytes.Repeat([]byte("na"), 2))
        

        Output:

        banana
        

        func Replace

        func Replace(s, old, new []byte, n int) []byte

        Replace returns a copy of the slice s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the slice and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune slice. If n < 0, there is no limit on the number of replacements.

        Example

        Code:

        fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("k"), []byte("ky"), 2))
        fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("oink"), []byte("moo"), -1))
        

        Output:

        oinky oinky oink
        moo moo moo
        

        func ReplaceAll

        func ReplaceAll(s, old, new []byte) []byte

        ReplaceAll returns a copy of the slice s with all non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the slice and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune slice.

        Example

        Code:

        fmt.Printf("%s\n", bytes.ReplaceAll([]byte("oink oink oink"), []byte("oink"), []byte("moo")))
        

        Output:

        moo moo moo
        

        func Runes

        func Runes(s []byte) []rune

        Runes interprets s as a sequence of UTF-8-encoded code points. It returns a slice of runes (Unicode code points) equivalent to s.

        Example

        Code:

        rs := bytes.Runes([]byte("go gopher"))
        for _, r := range rs {
            fmt.Printf("%#U\n", r)
        }
        

        Output:

        U+0067 'g'
        U+006F 'o'
        U+0020 ' '
        U+0067 'g'
        U+006F 'o'
        U+0070 'p'
        U+0068 'h'
        U+0065 'e'
        U+0072 'r'
        

        func Split

        func Split(s, sep []byte) [][]byte

        Split slices s into all subslices separated by sep and returns a slice of the subslices between those separators. If sep is empty, Split splits after each UTF-8 sequence. It is equivalent to SplitN with a count of -1.

        To split around the first instance of a separator, see Cut.

        Example

        Code:

        fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(",")))
        fmt.Printf("%q\n", bytes.Split([]byte("a man a plan a canal panama"), []byte("a ")))
        fmt.Printf("%q\n", bytes.Split([]byte(" xyz "), []byte("")))
        fmt.Printf("%q\n", bytes.Split([]byte(""), []byte("Bernardo O'Higgins")))
        

        Output:

        ["a" "b" "c"]
        ["" "man " "plan " "canal panama"]
        [" " "x" "y" "z" " "]
        [""]
        

        func SplitAfter

        func SplitAfter(s, sep []byte) [][]byte

        SplitAfter slices s into all subslices after each instance of sep and returns a slice of those subslices. If sep is empty, SplitAfter splits after each UTF-8 sequence. It is equivalent to SplitAfterN with a count of -1.

        Example

        Code:

        fmt.Printf("%q\n", bytes.SplitAfter([]byte("a,b,c"), []byte(",")))
        

        Output:

        ["a," "b," "c"]
        

        func SplitAfterN

        func SplitAfterN(s, sep []byte, n int) [][]byte

        SplitAfterN slices s into subslices after each instance of sep and returns a slice of those subslices. If sep is empty, SplitAfterN splits after each UTF-8 sequence. The count determines the number of subslices to return:

        n > 0: at most n subslices; the last subslice will be the unsplit remainder.
        n == 0: the result is nil (zero subslices)
        n < 0: all subslices
        

        Example

        Code:

        fmt.Printf("%q\n", bytes.SplitAfterN([]byte("a,b,c"), []byte(","), 2))
        

        Output:

        ["a," "b,c"]
        

        func SplitN

        func SplitN(s, sep []byte, n int) [][]byte

        SplitN slices s into subslices separated by sep and returns a slice of the subslices between those separators. If sep is empty, SplitN splits after each UTF-8 sequence. The count determines the number of subslices to return:

        n > 0: at most n subslices; the last subslice will be the unsplit remainder.
        n == 0: the result is nil (zero subslices)
        n < 0: all subslices
        

        To split around the first instance of a separator, see Cut.

        Example

        Code:

        fmt.Printf("%q\n", bytes.SplitN([]byte("a,b,c"), []byte(","), 2))
        z := bytes.SplitN([]byte("a,b,c"), []byte(","), 0)
        fmt.Printf("%q (nil = %v)\n", z, z == nil)
        

        Output:

        ["a" "b,c"]
        [] (nil = true)
        

        func Title

        func Title(s []byte) []byte

        Title treats s as UTF-8-encoded bytes and returns a copy with all Unicode letters that begin words mapped to their title case.

        Deprecated: The rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.

        Example

        Code:

        fmt.Printf("%s", bytes.Title([]byte("her royal highness")))
        

        Output:

        Her Royal Highness
        

        func ToLower

        func ToLower(s []byte) []byte

        ToLower returns a copy of the byte slice s with all Unicode letters mapped to their lower case.

        Example

        Code:

        fmt.Printf("%s", bytes.ToLower([]byte("Gopher")))
        

        Output:

        gopher
        

        func ToLowerSpecial

        func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte

        ToLowerSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their lower case, giving priority to the special casing rules.

        Example

        Code:

        str := []byte("AHOJ VÝVOJÁRİ GOLANG")
        totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str)
        fmt.Println("Original : " + string(str))
        fmt.Println("ToLower : " + string(totitle))
        

        Output:

        Original : AHOJ VÝVOJÁRİ GOLANG
        ToLower : ahoj vývojári golang
        

        func ToTitle

        func ToTitle(s []byte) []byte

        ToTitle treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their title case.

        Example

        Code:

        fmt.Printf("%s\n", bytes.ToTitle([]byte("loud noises")))
        fmt.Printf("%s\n", bytes.ToTitle([]byte("хлеб")))
        

        Output:

        LOUD NOISES
        ХЛЕБ
        

        func ToTitleSpecial

        func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte

        ToTitleSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their title case, giving priority to the special casing rules.

        Example

        Code:

        str := []byte("ahoj vývojári golang")
        totitle := bytes.ToTitleSpecial(unicode.AzeriCase, str)
        fmt.Println("Original : " + string(str))
        fmt.Println("ToTitle : " + string(totitle))
        

        Output:

        Original : ahoj vývojári golang
        ToTitle : AHOJ VÝVOJÁRİ GOLANG
        

        func ToUpper

        func ToUpper(s []byte) []byte

        ToUpper returns a copy of the byte slice s with all Unicode letters mapped to their upper case.

        Example

        Code:

        fmt.Printf("%s", bytes.ToUpper([]byte("Gopher")))
        

        Output:

        GOPHER
        

        func ToUpperSpecial

        func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte

        ToUpperSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their upper case, giving priority to the special casing rules.

        Example

        Code:

        str := []byte("ahoj vývojári golang")
        totitle := bytes.ToUpperSpecial(unicode.AzeriCase, str)
        fmt.Println("Original : " + string(str))
        fmt.Println("ToUpper : " + string(totitle))
        

        Output:

        Original : ahoj vývojári golang
        ToUpper : AHOJ VÝVOJÁRİ GOLANG
        

        func ToValidUTF8

        func ToValidUTF8(s, replacement []byte) []byte

        ToValidUTF8 treats s as UTF-8-encoded bytes and returns a copy with each run of bytes representing invalid UTF-8 replaced with the bytes in replacement, which may be empty.

        Example

        Code:

        fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("abc"), []byte("\uFFFD")))
        fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("a\xffb\xC0\xAFc\xff"), []byte("")))
        fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("\xed\xa0\x80"), []byte("abc")))
        

        Output:

        abc
        abc
        abc
        

        func Trim

        func Trim(s []byte, cutset string) []byte

        Trim returns a subslice of s by slicing off all leading and trailing UTF-8-encoded code points contained in cutset.

        Example

        Code:

        fmt.Printf("[%q]", bytes.Trim([]byte(" !!! Achtung! Achtung! !!! "), "! "))
        

        Output:

        ["Achtung! Achtung"]
        

        func TrimFunc

        func TrimFunc(s []byte, f func(r rune) bool) []byte

        TrimFunc returns a subslice of s by slicing off all leading and trailing UTF-8-encoded code points c that satisfy f(c).

        Example

        Code:

        fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsLetter)))
        fmt.Println(string(bytes.TrimFunc([]byte("\"go-gopher!\""), unicode.IsLetter)))
        fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsPunct)))
        fmt.Println(string(bytes.TrimFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
        

        Output:

        -gopher!
        "go-gopher!"
        go-gopher
        go-gopher!
        

        func TrimLeft

        func TrimLeft(s []byte, cutset string) []byte

        TrimLeft returns a subslice of s by slicing off all leading UTF-8-encoded code points contained in cutset.

        Example

        Code:

        fmt.Print(string(bytes.TrimLeft([]byte("453gopher8257"), "0123456789")))
        

        Output:

        gopher8257
        

        func TrimLeftFunc

        func TrimLeftFunc(s []byte, f func(r rune) bool) []byte

        TrimLeftFunc treats s as UTF-8-encoded bytes and returns a subslice of s by slicing off all leading UTF-8-encoded code points c that satisfy f(c).

        Example

        Code:

        fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher"), unicode.IsLetter)))
        fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher!"), unicode.IsPunct)))
        fmt.Println(string(bytes.TrimLeftFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
        

        Output:

        -gopher
        go-gopher!
        go-gopher!567
        

        func TrimPrefix

        func TrimPrefix(s, prefix []byte) []byte

        TrimPrefix returns s without the provided leading prefix string. If s doesn't start with prefix, s is returned unchanged.

        Example

        Code:

        var b = []byte("Goodbye,, world!")
        b = bytes.TrimPrefix(b, []byte("Goodbye,"))
        b = bytes.TrimPrefix(b, []byte("See ya,"))
        fmt.Printf("Hello%s", b)
        

        Output:

        Hello, world!
        

        func TrimRight

        func TrimRight(s []byte, cutset string) []byte

        TrimRight returns a subslice of s by slicing off all trailing UTF-8-encoded code points that are contained in cutset.

        Example

        Code:

        fmt.Print(string(bytes.TrimRight([]byte("453gopher8257"), "0123456789")))
        

        Output:

        453gopher
        

        func TrimRightFunc

        func TrimRightFunc(s []byte, f func(r rune) bool) []byte

        TrimRightFunc returns a subslice of s by slicing off all trailing UTF-8-encoded code points c that satisfy f(c).

        Example

        Code:

        fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher"), unicode.IsLetter)))
        fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher!"), unicode.IsPunct)))
        fmt.Println(string(bytes.TrimRightFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
        

        Output:

        go-
        go-gopher
        1234go-gopher!
        

        func TrimSpace

        func TrimSpace(s []byte) []byte

        TrimSpace returns a subslice of s by slicing off all leading and trailing white space, as defined by Unicode.

        Example

        Code:

        fmt.Printf("%s", bytes.TrimSpace([]byte(" \t\n a lone gopher \n\t\r\n")))
        

        Output:

        a lone gopher
        

        func TrimSuffix

        func TrimSuffix(s, suffix []byte) []byte

        TrimSuffix returns s without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.

        Example

        Code:

        var b = []byte("Hello, goodbye, etc!")
        b = bytes.TrimSuffix(b, []byte("goodbye, etc!"))
        b = bytes.TrimSuffix(b, []byte("gopher"))
        b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...)
        os.Stdout.Write(b)
        

        Output:

        Hello, world!
        

        type Buffer

        A Buffer is a variable-sized buffer of bytes with Buffer.Read and Buffer.Write methods. The zero value for Buffer is an empty buffer ready to use.

        type Buffer struct {
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        var b bytes.Buffer // A Buffer needs no initialization.
        b.Write([]byte("Hello "))
        fmt.Fprintf(&b, "world!")
        b.WriteTo(os.Stdout)
        

        Output:

        Hello world!
        

        Example (Reader)

        Code:

        // A Buffer can turn a string or a []byte into an io.Reader.
        buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==")
        dec := base64.NewDecoder(base64.StdEncoding, buf)
        io.Copy(os.Stdout, dec)
        

        Output:

        Gophers rule!
        

        func NewBuffer

        func NewBuffer(buf []byte) *Buffer

        NewBuffer creates and initializes a new Buffer using buf as its initial contents. The new Buffer takes ownership of buf, and the caller should not use buf after this call. NewBuffer is intended to prepare a Buffer to read existing data. It can also be used to set the initial size of the internal buffer for writing. To do that, buf should have the desired capacity but a length of zero.

        In most cases, new(Buffer) (or just declaring a Buffer variable) is sufficient to initialize a Buffer.

        func NewBufferString

        func NewBufferString(s string) *Buffer

        NewBufferString creates and initializes a new Buffer using string s as its initial contents. It is intended to prepare a buffer to read an existing string.

        In most cases, new(Buffer) (or just declaring a Buffer variable) is sufficient to initialize a Buffer.

        func (*Buffer) Available

        func (b *Buffer) Available() int

        Available returns how many bytes are unused in the buffer.

        func (*Buffer) AvailableBuffer

        func (b *Buffer) AvailableBuffer() []byte

        AvailableBuffer returns an empty buffer with b.Available() capacity. This buffer is intended to be appended to and passed to an immediately succeeding Buffer.Write call. The buffer is only valid until the next write operation on b.

        Example

        Code:

        var buf bytes.Buffer
        for i := 0; i < 4; i++ {
            b := buf.AvailableBuffer()
            b = strconv.AppendInt(b, int64(i), 10)
            b = append(b, ' ')
            buf.Write(b)
        }
        os.Stdout.Write(buf.Bytes())
        

        Output:

        0 1 2 3
        

        func (*Buffer) Bytes

        func (b *Buffer) Bytes() []byte

        Bytes returns a slice of length b.Len() holding the unread portion of the buffer. The slice is valid for use only until the next buffer modification (that is, only until the next call to a method like Buffer.Read, Buffer.Write, Buffer.Reset, or Buffer.Truncate). The slice aliases the buffer content at least until the next buffer modification, so immediate changes to the slice will affect the result of future reads.

        Example

        Code:

        buf := bytes.Buffer{}
        buf.Write([]byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'})
        os.Stdout.Write(buf.Bytes())
        

        Output:

        hello world
        

        func (*Buffer) Cap

        func (b *Buffer) Cap() int

        Cap returns the capacity of the buffer's underlying byte slice, that is, the total space allocated for the buffer's data.

        Example

        Code:

        buf1 := bytes.NewBuffer(make([]byte, 10))
        buf2 := bytes.NewBuffer(make([]byte, 0, 10))
        fmt.Println(buf1.Cap())
        fmt.Println(buf2.Cap())
        

        Output:

        10
        10
        

        func (*Buffer) Grow

        func (b *Buffer) Grow(n int)

        Grow grows the buffer's capacity, if necessary, to guarantee space for another n bytes. After Grow(n), at least n bytes can be written to the buffer without another allocation. If n is negative, Grow will panic. If the buffer can't grow it will panic with ErrTooLarge.

        Example

        Code:

        var b bytes.Buffer
        b.Grow(64)
        bb := b.Bytes()
        b.Write([]byte("64 bytes or fewer"))
        fmt.Printf("%q", bb[:b.Len()])
        

        Output:

        "64 bytes or fewer"
        

        func (*Buffer) Len

        func (b *Buffer) Len() int

        Len returns the number of bytes of the unread portion of the buffer; b.Len() == len(b.Bytes()).

        Example

        Code:

        var b bytes.Buffer
        b.Grow(64)
        b.Write([]byte("abcde"))
        fmt.Printf("%d", b.Len())
        

        Output:

        5
        

        func (*Buffer) Next

        func (b *Buffer) Next(n int) []byte

        Next returns a slice containing the next n bytes from the buffer, advancing the buffer as if the bytes had been returned by Buffer.Read. If there are fewer than n bytes in the buffer, Next returns the entire buffer. The slice is only valid until the next call to a read or write method.

        Example

        Code:

        var b bytes.Buffer
        b.Grow(64)
        b.Write([]byte("abcde"))
        fmt.Printf("%s\n", b.Next(2))
        fmt.Printf("%s\n", b.Next(2))
        fmt.Printf("%s", b.Next(2))
        

        Output:

        ab
        cd
        e
        

        func (*Buffer) Read

        func (b *Buffer) Read(p []byte) (n int, err error)

        Read reads the next len(p) bytes from the buffer or until the buffer is drained. The return value n is the number of bytes read. If the buffer has no data to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.

        Example

        Code:

        var b bytes.Buffer
        b.Grow(64)
        b.Write([]byte("abcde"))
        rdbuf := make([]byte, 1)
        n, err := b.Read(rdbuf)
        if err != nil {
            panic(err)
        }
        fmt.Println(n)
        fmt.Println(b.String())
        fmt.Println(string(rdbuf))
        // Output
        // 1
        // bcde
        // a
        

        func (*Buffer) ReadByte

        func (b *Buffer) ReadByte() (byte, error)

        ReadByte reads and returns the next byte from the buffer. If no byte is available, it returns error io.EOF.

        Example

        Code:

        var b bytes.Buffer
        b.Grow(64)
        b.Write([]byte("abcde"))
        c, err := b.ReadByte()
        if err != nil {
            panic(err)
        }
        fmt.Println(c)
        fmt.Println(b.String())
        // Output
        // 97
        // bcde
        

        func (*Buffer) ReadBytes

        func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)

        ReadBytes reads until the first occurrence of delim in the input, returning a slice containing the data up to and including the delimiter. If ReadBytes encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadBytes returns err != nil if and only if the returned data does not end in delim.

        func (*Buffer) ReadFrom

        func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)

        ReadFrom reads data from r until EOF and appends it to the buffer, growing the buffer as needed. The return value n is the number of bytes read. Any error except io.EOF encountered during the read is also returned. If the buffer becomes too large, ReadFrom will panic with ErrTooLarge.

        func (*Buffer) ReadRune

        func (b *Buffer) ReadRune() (r rune, size int, err error)

        ReadRune reads and returns the next UTF-8-encoded Unicode code point from the buffer. If no bytes are available, the error returned is io.EOF. If the bytes are an erroneous UTF-8 encoding, it consumes one byte and returns U+FFFD, 1.

        func (*Buffer) ReadString

        func (b *Buffer) ReadString(delim byte) (line string, err error)

        ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim.

        func (*Buffer) Reset

        func (b *Buffer) Reset()

        Reset resets the buffer to be empty, but it retains the underlying storage for use by future writes. Reset is the same as Buffer.Truncate(0).

        func (*Buffer) String

        func (b *Buffer) String() string

        String returns the contents of the unread portion of the buffer as a string. If the Buffer is a nil pointer, it returns "<nil>".

        To build strings more efficiently, see the strings.Builder type.

        func (*Buffer) Truncate

        func (b *Buffer) Truncate(n int)

        Truncate discards all but the first n unread bytes from the buffer but continues to use the same allocated storage. It panics if n is negative or greater than the length of the buffer.

        func (*Buffer) UnreadByte

        func (b *Buffer) UnreadByte() error

        UnreadByte unreads the last byte returned by the most recent successful read operation that read at least one byte. If a write has happened since the last read, if the last read returned an error, or if the read read zero bytes, UnreadByte returns an error.

        func (*Buffer) UnreadRune

        func (b *Buffer) UnreadRune() error

        UnreadRune unreads the last rune returned by Buffer.ReadRune. If the most recent read or write operation on the buffer was not a successful Buffer.ReadRune, UnreadRune returns an error. (In this regard it is stricter than Buffer.UnreadByte, which will unread the last byte from any read operation.)

        func (*Buffer) Write

        func (b *Buffer) Write(p []byte) (n int, err error)

        Write appends the contents of p to the buffer, growing the buffer as needed. The return value n is the length of p; err is always nil. If the buffer becomes too large, Write will panic with ErrTooLarge.

        func (*Buffer) WriteByte

        func (b *Buffer) WriteByte(c byte) error

        WriteByte appends the byte c to the buffer, growing the buffer as needed. The returned error is always nil, but is included to match bufio.Writer's WriteByte. If the buffer becomes too large, WriteByte will panic with ErrTooLarge.

        func (*Buffer) WriteRune

        func (b *Buffer) WriteRune(r rune) (n int, err error)

        WriteRune appends the UTF-8 encoding of Unicode code point r to the buffer, returning its length and an error, which is always nil but is included to match bufio.Writer's WriteRune. The buffer is grown as needed; if it becomes too large, WriteRune will panic with ErrTooLarge.

        func (*Buffer) WriteString

        func (b *Buffer) WriteString(s string) (n int, err error)

        WriteString appends the contents of s to the buffer, growing the buffer as needed. The return value n is the length of s; err is always nil. If the buffer becomes too large, WriteString will panic with ErrTooLarge.

        func (*Buffer) WriteTo

        func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)

        WriteTo writes data to w until the buffer is drained or an error occurs. The return value n is the number of bytes written; it always fits into an int, but it is int64 to match the io.WriterTo interface. Any error encountered during the write is also returned.

        type Reader

        A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker, io.ByteScanner, and io.RuneScanner interfaces by reading from a byte slice. Unlike a Buffer, a Reader is read-only and supports seeking. The zero value for Reader operates like a Reader of an empty slice.

        type Reader struct {
            // contains filtered or unexported fields
        }
        

        func NewReader

        func NewReader(b []byte) *Reader

        NewReader returns a new [Reader.Reader] reading from b.

        func (*Reader) Len

        func (r *Reader) Len() int

        Len returns the number of bytes of the unread portion of the slice.

        Example

        Code:

        fmt.Println(bytes.NewReader([]byte("Hi!")).Len())
        fmt.Println(bytes.NewReader([]byte("こんにちは!")).Len())
        

        Output:

        3
        16
        

        func (*Reader) Read

        func (r *Reader) Read(b []byte) (n int, err error)

        Read implements the io.Reader interface.

        func (*Reader) ReadAt

        func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)

        ReadAt implements the io.ReaderAt interface.

        func (*Reader) ReadByte

        func (r *Reader) ReadByte() (byte, error)

        ReadByte implements the io.ByteReader interface.

        func (*Reader) ReadRune

        func (r *Reader) ReadRune() (ch rune, size int, err error)

        ReadRune implements the io.RuneReader interface.

        func (*Reader) Reset

        func (r *Reader) Reset(b []byte)

        Reset resets the [Reader.Reader] to be reading from b.

        func (*Reader) Seek

        func (r *Reader) Seek(offset int64, whence int) (int64, error)

        Seek implements the io.Seeker interface.

        func (*Reader) Size

        func (r *Reader) Size() int64

        Size returns the original length of the underlying byte slice. Size is the number of bytes available for reading via Reader.ReadAt. The result is unaffected by any method calls except Reader.Reset.

        func (*Reader) UnreadByte

        func (r *Reader) UnreadByte() error

        UnreadByte complements Reader.ReadByte in implementing the io.ByteScanner interface.

        func (*Reader) UnreadRune

        func (r *Reader) UnreadRune() error

        UnreadRune complements Reader.ReadRune in implementing the io.RuneScanner interface.

        func (*Reader) WriteTo

        func (r *Reader) WriteTo(w io.Writer) (n int64, err error)

        WriteTo implements the io.WriterTo interface.

        cmp - Go Documentation Server
        ...

        Package cmp

        import "cmp"
        Overview
        Index
        Examples

        Overview ▾

        Package cmp provides types and functions related to comparing ordered values.

        func Compare

        func Compare[T Ordered](x, y T) int

        Compare returns

        -1 if x is less than y,
         0 if x equals y,
        +1 if x is greater than y.
        

        For floating-point types, a NaN is considered less than any non-NaN, a NaN is considered equal to a NaN, and -0.0 is equal to 0.0.

        func Less

        func Less[T Ordered](x, y T) bool

        Less reports whether x is less than y. For floating-point types, a NaN is considered less than any non-NaN, and -0.0 is not less than (is equal to) 0.0.

        func Or

        func Or[T comparable](vals ...T) T

        Or returns the first of its arguments that is not equal to the zero value. If no argument is non-zero, it returns the zero value.

        Example

        Code:

        // Suppose we have some user input
        // that may or may not be an empty string
        userInput1 := ""
        userInput2 := "some text"
        
        fmt.Println(cmp.Or(userInput1, "default"))
        fmt.Println(cmp.Or(userInput2, "default"))
        fmt.Println(cmp.Or(userInput1, userInput2, "default"))
        

        Output:

        default
        some text
        some text
        

        Example (Sort)

        Code:

        type Order struct {
            Product  string
            Customer string
            Price    float64
        }
        orders := []Order{
            {"foo", "alice", 1.00},
            {"bar", "bob", 3.00},
            {"baz", "carol", 4.00},
            {"foo", "alice", 2.00},
            {"bar", "carol", 1.00},
            {"foo", "bob", 4.00},
        }
        // Sort by customer first, product second, and last by higher price
        slices.SortFunc(orders, func(a, b Order) int {
            return cmp.Or(
                cmp.Compare(a.Customer, b.Customer),
                cmp.Compare(a.Product, b.Product),
                cmp.Compare(b.Price, a.Price),
            )
        })
        for _, order := range orders {
            fmt.Printf("%s %s %.2f\n", order.Product, order.Customer, order.Price)
        }
        
        

        Output:

        foo alice 2.00
        foo alice 1.00
        bar bob 3.00
        foo bob 4.00
        bar carol 1.00
        baz carol 4.00
        

        type Ordered

        Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >. If future releases of Go add new ordered types, this constraint will be modified to include them.

        Note that floating-point types may contain NaN ("not-a-number") values. An operator such as == or < will always report false when comparing a NaN value with any other value, NaN or not. See the Compare function for a consistent way to compare NaN values.

        type Ordered interface {
            ~int | ~int8 | ~int16 | ~int32 | ~int64 |
                ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
                ~float32 | ~float64 |
                ~string
        }
        /src/compress - Go Documentation Server
        ...

        Directory /src/compress

        Name Synopsis
        ..
        bzip2 Package bzip2 implements bzip2 decompression.
        flate Package flate implements the DEFLATE compressed data format, described in RFC 1951.
        gzip Package gzip implements reading and writing of gzip format compressed files, as specified in RFC 1952.
        lzw Package lzw implements the Lempel-Ziv-Welch compressed data format, described in T. A. Welch, “A Technique for High-Performance Data Compression”, Computer, 17(6) (June 1984), pp 8-19.
        zlib Package zlib implements reading and writing of zlib format compressed data, as specified in RFC 1950.
        bzip2 - Go Documentation Server
        ...

        Package bzip2

        import "compress/bzip2"
        Overview
        Index

        Overview ▾

        Package bzip2 implements bzip2 decompression.

        func NewReader

        func NewReader(r io.Reader) io.Reader

        NewReader returns an io.Reader which decompresses bzip2 data from r. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r.

        type StructuralError

        A StructuralError is returned when the bzip2 data is found to be syntactically invalid.

        type StructuralError string

        func (StructuralError) Error

        func (s StructuralError) Error() string
        flate - Go Documentation Server
        ...

        Package flate

        import "compress/flate"
        Overview
        Index
        Examples

        Overview ▾

        Package flate implements the DEFLATE compressed data format, described in RFC 1951. The gzip and zlib packages implement access to DEFLATE-based file formats.

        Example (Dictionary)

        A preset dictionary can be used to improve the compression ratio. The downside to using a dictionary is that the compressor and decompressor must agree in advance what dictionary to use.

        Code:

        // The dictionary is a string of bytes. When compressing some input data,
        // the compressor will attempt to substitute substrings with matches found
        // in the dictionary. As such, the dictionary should only contain substrings
        // that are expected to be found in the actual data stream.
        const dict = `<?xml version="1.0"?>` + `<book>` + `<data>` + `<meta name="` + `" content="`
        
        // The data to compress should (but is not required to) contain frequent
        // substrings that match those in the dictionary.
        const data = `<?xml version="1.0"?>
        <book>
            <meta name="title" content="The Go Programming Language"/>
            <meta name="authors" content="Alan Donovan and Brian Kernighan"/>
            <meta name="published" content="2015-10-26"/>
            <meta name="isbn" content="978-0134190440"/>
            <data>...</data>
        </book>
        `
        
        var b bytes.Buffer
        
        // Compress the data using the specially crafted dictionary.
        zw, err := flate.NewWriterDict(&b, flate.DefaultCompression, []byte(dict))
        if err != nil {
            log.Fatal(err)
        }
        if _, err := io.Copy(zw, strings.NewReader(data)); err != nil {
            log.Fatal(err)
        }
        if err := zw.Close(); err != nil {
            log.Fatal(err)
        }
        
        // The decompressor must use the same dictionary as the compressor.
        // Otherwise, the input may appear as corrupted.
        fmt.Println("Decompressed output using the dictionary:")
        zr := flate.NewReaderDict(bytes.NewReader(b.Bytes()), []byte(dict))
        if _, err := io.Copy(os.Stdout, zr); err != nil {
            log.Fatal(err)
        }
        if err := zr.Close(); err != nil {
            log.Fatal(err)
        }
        
        fmt.Println()
        
        // Substitute all of the bytes in the dictionary with a '#' to visually
        // demonstrate the approximate effectiveness of using a preset dictionary.
        fmt.Println("Substrings matched by the dictionary are marked with #:")
        hashDict := []byte(dict)
        for i := range hashDict {
            hashDict[i] = '#'
        }
        zr = flate.NewReaderDict(&b, hashDict)
        if _, err := io.Copy(os.Stdout, zr); err != nil {
            log.Fatal(err)
        }
        if err := zr.Close(); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        Decompressed output using the dictionary:
        <?xml version="1.0"?>
        <book>
        	<meta name="title" content="The Go Programming Language"/>
        	<meta name="authors" content="Alan Donovan and Brian Kernighan"/>
        	<meta name="published" content="2015-10-26"/>
        	<meta name="isbn" content="978-0134190440"/>
        	<data>...</data>
        </book>
        
        Substrings matched by the dictionary are marked with #:
        #####################
        ######
        	############title###########The Go Programming Language"/#
        	############authors###########Alan Donovan and Brian Kernighan"/#
        	############published###########2015-10-26"/#
        	############isbn###########978-0134190440"/#
        	######...</#####
        </#####
        

        Example (Reset)

        In performance critical applications, Reset can be used to discard the current compressor or decompressor state and reinitialize them quickly by taking advantage of previously allocated memory.

        Code:

        proverbs := []string{
            "Don't communicate by sharing memory, share memory by communicating.\n",
            "Concurrency is not parallelism.\n",
            "The bigger the interface, the weaker the abstraction.\n",
            "Documentation is for users.\n",
        }
        
        var r strings.Reader
        var b bytes.Buffer
        buf := make([]byte, 32<<10)
        
        zw, err := flate.NewWriter(nil, flate.DefaultCompression)
        if err != nil {
            log.Fatal(err)
        }
        zr := flate.NewReader(nil)
        
        for _, s := range proverbs {
            r.Reset(s)
            b.Reset()
        
            // Reset the compressor and encode from some input stream.
            zw.Reset(&b)
            if _, err := io.CopyBuffer(zw, &r, buf); err != nil {
                log.Fatal(err)
            }
            if err := zw.Close(); err != nil {
                log.Fatal(err)
            }
        
            // Reset the decompressor and decode to some output stream.
            if err := zr.(flate.Resetter).Reset(&b, nil); err != nil {
                log.Fatal(err)
            }
            if _, err := io.CopyBuffer(os.Stdout, zr, buf); err != nil {
                log.Fatal(err)
            }
            if err := zr.Close(); err != nil {
                log.Fatal(err)
            }
        }
        
        

        Output:

        Don't communicate by sharing memory, share memory by communicating.
        Concurrency is not parallelism.
        The bigger the interface, the weaker the abstraction.
        Documentation is for users.
        

        Example (Synchronization)

        DEFLATE is suitable for transmitting compressed data across the network.

        Code:

        var wg sync.WaitGroup
        defer wg.Wait()
        
        // Use io.Pipe to simulate a network connection.
        // A real network application should take care to properly close the
        // underlying connection.
        rp, wp := io.Pipe()
        
        // Start a goroutine to act as the transmitter.
        wg.Add(1)
        go func() {
            defer wg.Done()
        
            zw, err := flate.NewWriter(wp, flate.BestSpeed)
            if err != nil {
                log.Fatal(err)
            }
        
            b := make([]byte, 256)
            for _, m := range strings.Fields("A long time ago in a galaxy far, far away...") {
                // We use a simple framing format where the first byte is the
                // message length, followed the message itself.
                b[0] = uint8(copy(b[1:], m))
        
                if _, err := zw.Write(b[:1+len(m)]); err != nil {
                    log.Fatal(err)
                }
        
                // Flush ensures that the receiver can read all data sent so far.
                if err := zw.Flush(); err != nil {
                    log.Fatal(err)
                }
            }
        
            if err := zw.Close(); err != nil {
                log.Fatal(err)
            }
        }()
        
        // Start a goroutine to act as the receiver.
        wg.Add(1)
        go func() {
            defer wg.Done()
        
            zr := flate.NewReader(rp)
        
            b := make([]byte, 256)
            for {
                // Read the message length.
                // This is guaranteed to return for every corresponding
                // Flush and Close on the transmitter side.
                if _, err := io.ReadFull(zr, b[:1]); err != nil {
                    if err == io.EOF {
                        break // The transmitter closed the stream
                    }
                    log.Fatal(err)
                }
        
                // Read the message content.
                n := int(b[0])
                if _, err := io.ReadFull(zr, b[:n]); err != nil {
                    log.Fatal(err)
                }
        
                fmt.Printf("Received %d bytes: %s\n", n, b[:n])
            }
            fmt.Println()
        
            if err := zr.Close(); err != nil {
                log.Fatal(err)
            }
        }()
        
        

        Output:

        Received 1 bytes: A
        Received 4 bytes: long
        Received 4 bytes: time
        Received 3 bytes: ago
        Received 2 bytes: in
        Received 1 bytes: a
        Received 6 bytes: galaxy
        Received 4 bytes: far,
        Received 3 bytes: far
        Received 7 bytes: away...
        

        Constants

        const (
            NoCompression      = 0
            BestSpeed          = 1
            BestCompression    = 9
            DefaultCompression = -1
        
            // HuffmanOnly disables Lempel-Ziv match searching and only performs Huffman
            // entropy encoding. This mode is useful in compressing data that has
            // already been compressed with an LZ style algorithm (e.g. Snappy or LZ4)
            // that lacks an entropy encoder. Compression gains are achieved when
            // certain bytes in the input stream occur more frequently than others.
            //
            // Note that HuffmanOnly produces a compressed output that is
            // RFC 1951 compliant. That is, any valid DEFLATE decompressor will
            // continue to be able to decompress this output.
            HuffmanOnly = -2
        )

        func NewReader

        func NewReader(r io.Reader) io.ReadCloser

        NewReader returns a new ReadCloser that can be used to read the uncompressed version of r. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r. The reader returns io.EOF after the final block in the DEFLATE stream has been encountered. Any trailing data after the final block is ignored.

        The io.ReadCloser returned by NewReader also implements Resetter.

        func NewReaderDict

        func NewReaderDict(r io.Reader, dict []byte) io.ReadCloser

        NewReaderDict is like NewReader but initializes the reader with a preset dictionary. The returned Reader behaves as if the uncompressed data stream started with the given dictionary, which has already been read. NewReaderDict is typically used to read data compressed by NewWriterDict.

        The ReadCloser returned by NewReaderDict also implements Resetter.

        type CorruptInputError

        A CorruptInputError reports the presence of corrupt input at a given offset.

        type CorruptInputError int64

        func (CorruptInputError) Error

        func (e CorruptInputError) Error() string

        type InternalError

        An InternalError reports an error in the flate code itself.

        type InternalError string

        func (InternalError) Error

        func (e InternalError) Error() string

        type ReadError

        A ReadError reports an error encountered while reading input.

        Deprecated: No longer returned.

        type ReadError struct {
            Offset int64 // byte offset where error occurred
            Err    error // error returned by underlying Read
        }
        

        func (*ReadError) Error

        func (e *ReadError) Error() string

        type Reader

        The actual read interface needed by NewReader. If the passed in io.Reader does not also have ReadByte, the NewReader will introduce its own buffering.

        type Reader interface {
            io.Reader
            io.ByteReader
        }

        type Resetter

        Resetter resets a ReadCloser returned by NewReader or NewReaderDict to switch to a new underlying Reader. This permits reusing a ReadCloser instead of allocating a new one.

        type Resetter interface {
            // Reset discards any buffered data and resets the Resetter as if it was
            // newly initialized with the given reader.
            Reset(r io.Reader, dict []byte) error
        }

        type WriteError

        A WriteError reports an error encountered while writing output.

        Deprecated: No longer returned.

        type WriteError struct {
            Offset int64 // byte offset where error occurred
            Err    error // error returned by underlying Write
        }
        

        func (*WriteError) Error

        func (e *WriteError) Error() string

        type Writer

        A Writer takes data written to it and writes the compressed form of that data to an underlying writer (see NewWriter).

        type Writer struct {
            // contains filtered or unexported fields
        }
        

        func NewWriter

        func NewWriter(w io.Writer, level int) (*Writer, error)

        NewWriter returns a new Writer compressing data at the given level. Following zlib, levels range from 1 (BestSpeed) to 9 (BestCompression); higher levels typically run slower but compress more. Level 0 (NoCompression) does not attempt any compression; it only adds the necessary DEFLATE framing. Level -1 (DefaultCompression) uses the default compression level. Level -2 (HuffmanOnly) will use Huffman compression only, giving a very fast compression for all types of input, but sacrificing considerable compression efficiency.

        If level is in the range [-2, 9] then the error returned will be nil. Otherwise the error returned will be non-nil.

        func NewWriterDict

        func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error)

        NewWriterDict is like NewWriter but initializes the new Writer with a preset dictionary. The returned Writer behaves as if the dictionary had been written to it without producing any compressed output. The compressed data written to w can only be decompressed by a Reader initialized with the same dictionary.

        func (*Writer) Close

        func (w *Writer) Close() error

        Close flushes and closes the writer.

        func (*Writer) Flush

        func (w *Writer) Flush() error

        Flush flushes any pending data to the underlying writer. It is useful mainly in compressed network protocols, to ensure that a remote reader has enough data to reconstruct a packet. Flush does not return until the data has been written. Calling Flush when there is no pending data still causes the Writer to emit a sync marker of at least 4 bytes. If the underlying writer returns an error, Flush returns that error.

        In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.

        func (*Writer) Reset

        func (w *Writer) Reset(dst io.Writer)

        Reset discards the writer's state and makes it equivalent to the result of NewWriter or NewWriterDict called with dst and w's level and dictionary.

        func (*Writer) Write

        func (w *Writer) Write(data []byte) (n int, err error)

        Write writes data to w, which will eventually write the compressed form of data to its underlying writer.

        gzip - Go Documentation Server
        ...

        Package gzip

        import "compress/gzip"
        Overview
        Index
        Examples

        Overview ▾

        Package gzip implements reading and writing of gzip format compressed files, as specified in RFC 1952.

        Example (CompressingReader)

        Code:

        // This is an example of writing a compressing reader.
        // This can be useful for an HTTP client body, as shown.
        
        const testdata = "the data to be compressed"
        
        // This HTTP handler is just for testing purposes.
        handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
            zr, err := gzip.NewReader(req.Body)
            if err != nil {
                log.Fatal(err)
            }
        
            // Just output the data for the example.
            if _, err := io.Copy(os.Stdout, zr); err != nil {
                log.Fatal(err)
            }
        })
        ts := httptest.NewServer(handler)
        defer ts.Close()
        
        // The remainder is the example code.
        
        // The data we want to compress, as an io.Reader
        dataReader := strings.NewReader(testdata)
        
        // bodyReader is the body of the HTTP request, as an io.Reader.
        // httpWriter is the body of the HTTP request, as an io.Writer.
        bodyReader, httpWriter := io.Pipe()
        
        // Make sure that bodyReader is always closed, so that the
        // goroutine below will always exit.
        defer bodyReader.Close()
        
        // gzipWriter compresses data to httpWriter.
        gzipWriter := gzip.NewWriter(httpWriter)
        
        // errch collects any errors from the writing goroutine.
        errch := make(chan error, 1)
        
        go func() {
            defer close(errch)
            sentErr := false
            sendErr := func(err error) {
                if !sentErr {
                    errch <- err
                    sentErr = true
                }
            }
        
            // Copy our data to gzipWriter, which compresses it to
            // gzipWriter, which feeds it to bodyReader.
            if _, err := io.Copy(gzipWriter, dataReader); err != nil && err != io.ErrClosedPipe {
                sendErr(err)
            }
            if err := gzipWriter.Close(); err != nil && err != io.ErrClosedPipe {
                sendErr(err)
            }
            if err := httpWriter.Close(); err != nil && err != io.ErrClosedPipe {
                sendErr(err)
            }
        }()
        
        // Send an HTTP request to the test server.
        req, err := http.NewRequest("PUT", ts.URL, bodyReader)
        if err != nil {
            log.Fatal(err)
        }
        
        // Note that passing req to http.Client.Do promises that it
        // will close the body, in this case bodyReader.
        resp, err := ts.Client().Do(req)
        if err != nil {
            log.Fatal(err)
        }
        
        // Check whether there was an error compressing the data.
        if err := <-errch; err != nil {
            log.Fatal(err)
        }
        
        // For this example we don't care about the response.
        resp.Body.Close()
        
        

        Output:

        the data to be compressed
        

        Example (WriterReader)

        Code:

        var buf bytes.Buffer
        zw := gzip.NewWriter(&buf)
        
        // Setting the Header fields is optional.
        zw.Name = "a-new-hope.txt"
        zw.Comment = "an epic space opera by George Lucas"
        zw.ModTime = time.Date(1977, time.May, 25, 0, 0, 0, 0, time.UTC)
        
        _, err := zw.Write([]byte("A long time ago in a galaxy far, far away..."))
        if err != nil {
            log.Fatal(err)
        }
        
        if err := zw.Close(); err != nil {
            log.Fatal(err)
        }
        
        zr, err := gzip.NewReader(&buf)
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("Name: %s\nComment: %s\nModTime: %s\n\n", zr.Name, zr.Comment, zr.ModTime.UTC())
        
        if _, err := io.Copy(os.Stdout, zr); err != nil {
            log.Fatal(err)
        }
        
        if err := zr.Close(); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        Name: a-new-hope.txt
        Comment: an epic space opera by George Lucas
        ModTime: 1977-05-25 00:00:00 +0000 UTC
        
        A long time ago in a galaxy far, far away...
        

        Constants

        These constants are copied from the flate package, so that code that imports "compress/gzip" does not also have to import "compress/flate".

        const (
            NoCompression      = flate.NoCompression
            BestSpeed          = flate.BestSpeed
            BestCompression    = flate.BestCompression
            DefaultCompression = flate.DefaultCompression
            HuffmanOnly        = flate.HuffmanOnly
        )

        Variables

        var (
            // ErrChecksum is returned when reading GZIP data that has an invalid checksum.
            ErrChecksum = errors.New("gzip: invalid checksum")
            // ErrHeader is returned when reading GZIP data that has an invalid header.
            ErrHeader = errors.New("gzip: invalid header")
        )

        The gzip file stores a header giving metadata about the compressed file. That header is exposed as the fields of the Writer and Reader structs.

        Strings must be UTF-8 encoded and may only contain Unicode code points U+0001 through U+00FF, due to limitations of the GZIP file format.

        type Header struct {
            Comment string    // comment
            Extra   []byte    // "extra data"
            ModTime time.Time // modification time
            Name    string    // file name
            OS      byte      // operating system type
        }
        

        type Reader

        A Reader is an io.Reader that can be read to retrieve uncompressed data from a gzip-format compressed file.

        In general, a gzip file can be a concatenation of gzip files, each with its own header. Reads from the Reader return the concatenation of the uncompressed data of each. Only the first header is recorded in the Reader fields.

        Gzip files store a length and checksum of the uncompressed data. The Reader will return an ErrChecksum when Reader.Read reaches the end of the uncompressed data if it does not have the expected length or checksum. Clients should treat data returned by Reader.Read as tentative until they receive the io.EOF marking the end of the data.

        type Reader struct {
            Header // valid after NewReader or Reader.Reset
            // contains filtered or unexported fields
        }
        

        func NewReader

        func NewReader(r io.Reader) (*Reader, error)

        NewReader creates a new Reader reading the given reader. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r.

        It is the caller's responsibility to call Close on the Reader when done.

        The [Reader.Header] fields will be valid in the Reader returned.

        func (*Reader) Close

        func (z *Reader) Close() error

        Close closes the Reader. It does not close the underlying io.Reader. In order for the GZIP checksum to be verified, the reader must be fully consumed until the io.EOF.

        func (*Reader) Multistream

        func (z *Reader) Multistream(ok bool)

        Multistream controls whether the reader supports multistream files.

        If enabled (the default), the Reader expects the input to be a sequence of individually gzipped data streams, each with its own header and trailer, ending at EOF. The effect is that the concatenation of a sequence of gzipped files is treated as equivalent to the gzip of the concatenation of the sequence. This is standard behavior for gzip readers.

        Calling Multistream(false) disables this behavior; disabling the behavior can be useful when reading file formats that distinguish individual gzip data streams or mix gzip data streams with other data streams. In this mode, when the Reader reaches the end of the data stream, Reader.Read returns io.EOF. The underlying reader must implement io.ByteReader in order to be left positioned just after the gzip stream. To start the next stream, call z.Reset(r) followed by z.Multistream(false). If there is no next stream, z.Reset(r) will return io.EOF.

        Example

        Code:

        var buf bytes.Buffer
        zw := gzip.NewWriter(&buf)
        
        var files = []struct {
            name    string
            comment string
            modTime time.Time
            data    string
        }{
            {"file-1.txt", "file-header-1", time.Date(2006, time.February, 1, 3, 4, 5, 0, time.UTC), "Hello Gophers - 1"},
            {"file-2.txt", "file-header-2", time.Date(2007, time.March, 2, 4, 5, 6, 1, time.UTC), "Hello Gophers - 2"},
        }
        
        for _, file := range files {
            zw.Name = file.name
            zw.Comment = file.comment
            zw.ModTime = file.modTime
        
            if _, err := zw.Write([]byte(file.data)); err != nil {
                log.Fatal(err)
            }
        
            if err := zw.Close(); err != nil {
                log.Fatal(err)
            }
        
            zw.Reset(&buf)
        }
        
        zr, err := gzip.NewReader(&buf)
        if err != nil {
            log.Fatal(err)
        }
        
        for {
            zr.Multistream(false)
            fmt.Printf("Name: %s\nComment: %s\nModTime: %s\n\n", zr.Name, zr.Comment, zr.ModTime.UTC())
        
            if _, err := io.Copy(os.Stdout, zr); err != nil {
                log.Fatal(err)
            }
        
            fmt.Print("\n\n")
        
            err = zr.Reset(&buf)
            if err == io.EOF {
                break
            }
            if err != nil {
                log.Fatal(err)
            }
        }
        
        if err := zr.Close(); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        Name: file-1.txt
        Comment: file-header-1
        ModTime: 2006-02-01 03:04:05 +0000 UTC
        
        Hello Gophers - 1
        
        Name: file-2.txt
        Comment: file-header-2
        ModTime: 2007-03-02 04:05:06 +0000 UTC
        
        Hello Gophers - 2
        

        func (*Reader) Read

        func (z *Reader) Read(p []byte) (n int, err error)

        Read implements io.Reader, reading uncompressed bytes from its underlying Reader.

        func (*Reader) Reset

        func (z *Reader) Reset(r io.Reader) error

        Reset discards the Reader z's state and makes it equivalent to the result of its original state from NewReader, but reading from r instead. This permits reusing a Reader rather than allocating a new one.

        type Writer

        A Writer is an io.WriteCloser. Writes to a Writer are compressed and written to w.

        type Writer struct {
            Header // written at first call to Write, Flush, or Close
            // contains filtered or unexported fields
        }
        

        func NewWriter

        func NewWriter(w io.Writer) *Writer

        NewWriter returns a new Writer. Writes to the returned writer are compressed and written to w.

        It is the caller's responsibility to call Close on the Writer when done. Writes may be buffered and not flushed until Close.

        Callers that wish to set the fields in Writer.Header must do so before the first call to Write, Flush, or Close.

        func NewWriterLevel

        func NewWriterLevel(w io.Writer, level int) (*Writer, error)

        NewWriterLevel is like NewWriter but specifies the compression level instead of assuming DefaultCompression.

        The compression level can be DefaultCompression, NoCompression, HuffmanOnly or any integer value between BestSpeed and BestCompression inclusive. The error returned will be nil if the level is valid.

        func (*Writer) Close

        func (z *Writer) Close() error

        Close closes the Writer by flushing any unwritten data to the underlying io.Writer and writing the GZIP footer. It does not close the underlying io.Writer.

        func (*Writer) Flush

        func (z *Writer) Flush() error

        Flush flushes any pending compressed data to the underlying writer.

        It is useful mainly in compressed network protocols, to ensure that a remote reader has enough data to reconstruct a packet. Flush does not return until the data has been written. If the underlying writer returns an error, Flush returns that error.

        In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.

        func (*Writer) Reset

        func (z *Writer) Reset(w io.Writer)

        Reset discards the Writer z's state and makes it equivalent to the result of its original state from NewWriter or NewWriterLevel, but writing to w instead. This permits reusing a Writer rather than allocating a new one.

        func (*Writer) Write

        func (z *Writer) Write(p []byte) (int, error)

        Write writes a compressed form of p to the underlying io.Writer. The compressed bytes are not necessarily flushed until the Writer is closed.

        lzw - Go Documentation Server
        ...

        Package lzw

        import "compress/lzw"
        Overview
        Index

        Overview ▾

        Package lzw implements the Lempel-Ziv-Welch compressed data format, described in T. A. Welch, “A Technique for High-Performance Data Compression”, Computer, 17(6) (June 1984), pp 8-19.

        In particular, it implements LZW as used by the GIF and PDF file formats, which means variable-width codes up to 12 bits and the first two non-literal codes are a clear code and an EOF code.

        The TIFF file format uses a similar but incompatible version of the LZW algorithm. See the golang.org/x/image/tiff/lzw package for an implementation.

        func NewReader

        func NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser

        NewReader creates a new io.ReadCloser. Reads from the returned io.ReadCloser read and decompress data from r. If r does not also implement io.ByteReader, the decompressor may read more data than necessary from r. It is the caller's responsibility to call Close on the ReadCloser when finished reading. The number of bits to use for literal codes, litWidth, must be in the range [2,8] and is typically 8. It must equal the litWidth used during compression.

        It is guaranteed that the underlying type of the returned io.ReadCloser is a *Reader.

        func NewWriter

        func NewWriter(w io.Writer, order Order, litWidth int) io.WriteCloser

        NewWriter creates a new io.WriteCloser. Writes to the returned io.WriteCloser are compressed and written to w. It is the caller's responsibility to call Close on the WriteCloser when finished writing. The number of bits to use for literal codes, litWidth, must be in the range [2,8] and is typically 8. Input bytes must be less than 1<<litWidth.

        It is guaranteed that the underlying type of the returned io.WriteCloser is a *Writer.

        type Order

        Order specifies the bit ordering in an LZW data stream.

        type Order int
        const (
            // LSB means Least Significant Bits first, as used in the GIF file format.
            LSB Order = iota
            // MSB means Most Significant Bits first, as used in the TIFF and PDF
            // file formats.
            MSB
        )

        type Reader

        Reader is an io.Reader which can be used to read compressed data in the LZW format.

        type Reader struct {
            // contains filtered or unexported fields
        }
        

        func (*Reader) Close

        func (r *Reader) Close() error

        Close closes the Reader and returns an error for any future read operation. It does not close the underlying io.Reader.

        func (*Reader) Read

        func (r *Reader) Read(b []byte) (int, error)

        Read implements io.Reader, reading uncompressed bytes from its underlying Reader.

        func (*Reader) Reset

        func (r *Reader) Reset(src io.Reader, order Order, litWidth int)

        Reset clears the Reader's state and allows it to be reused again as a new Reader.

        type Writer

        Writer is an LZW compressor. It writes the compressed form of the data to an underlying writer (see NewWriter).

        type Writer struct {
            // contains filtered or unexported fields
        }
        

        func (*Writer) Close

        func (w *Writer) Close() error

        Close closes the Writer, flushing any pending output. It does not close w's underlying writer.

        func (*Writer) Reset

        func (w *Writer) Reset(dst io.Writer, order Order, litWidth int)

        Reset clears the Writer's state and allows it to be reused again as a new Writer.

        func (*Writer) Write

        func (w *Writer) Write(p []byte) (n int, err error)

        Write writes a compressed representation of p to w's underlying writer.

        zlib - Go Documentation Server
        ...

        Package zlib

        import "compress/zlib"
        Overview
        Index
        Examples

        Overview ▾

        Package zlib implements reading and writing of zlib format compressed data, as specified in RFC 1950.

        The implementation provides filters that uncompress during reading and compress during writing. For example, to write compressed data to a buffer:

        var b bytes.Buffer
        w := zlib.NewWriter(&b)
        w.Write([]byte("hello, world\n"))
        w.Close()
        

        and to read that data back:

        r, err := zlib.NewReader(&b)
        io.Copy(os.Stdout, r)
        r.Close()
        

        Constants

        These constants are copied from the flate package, so that code that imports "compress/zlib" does not also have to import "compress/flate".

        const (
            NoCompression      = flate.NoCompression
            BestSpeed          = flate.BestSpeed
            BestCompression    = flate.BestCompression
            DefaultCompression = flate.DefaultCompression
            HuffmanOnly        = flate.HuffmanOnly
        )

        Variables

        var (
            // ErrChecksum is returned when reading ZLIB data that has an invalid checksum.
            ErrChecksum = errors.New("zlib: invalid checksum")
            // ErrDictionary is returned when reading ZLIB data that has an invalid dictionary.
            ErrDictionary = errors.New("zlib: invalid dictionary")
            // ErrHeader is returned when reading ZLIB data that has an invalid header.
            ErrHeader = errors.New("zlib: invalid header")
        )

        func NewReader

        func NewReader(r io.Reader) (io.ReadCloser, error)

        NewReader creates a new ReadCloser. Reads from the returned ReadCloser read and decompress data from r. If r does not implement io.ByteReader, the decompressor may read more data than necessary from r. It is the caller's responsibility to call Close on the ReadCloser when done.

        The io.ReadCloser returned by NewReader also implements Resetter.

        Example

        Code:

        buff := []byte{120, 156, 202, 72, 205, 201, 201, 215, 81, 40, 207,
            47, 202, 73, 225, 2, 4, 0, 0, 255, 255, 33, 231, 4, 147}
        b := bytes.NewReader(buff)
        
        r, err := zlib.NewReader(b)
        if err != nil {
            panic(err)
        }
        io.Copy(os.Stdout, r)
        

        Output:

        hello, world
        

        func NewReaderDict

        func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, error)

        NewReaderDict is like NewReader but uses a preset dictionary. NewReaderDict ignores the dictionary if the compressed data does not refer to it. If the compressed data refers to a different dictionary, NewReaderDict returns ErrDictionary.

        The ReadCloser returned by NewReaderDict also implements Resetter.

        type Resetter

        Resetter resets a ReadCloser returned by NewReader or NewReaderDict to switch to a new underlying Reader. This permits reusing a ReadCloser instead of allocating a new one.

        type Resetter interface {
            // Reset discards any buffered data and resets the Resetter as if it was
            // newly initialized with the given reader.
            Reset(r io.Reader, dict []byte) error
        }

        type Writer

        A Writer takes data written to it and writes the compressed form of that data to an underlying writer (see NewWriter).

        type Writer struct {
            // contains filtered or unexported fields
        }
        

        func NewWriter

        func NewWriter(w io.Writer) *Writer

        NewWriter creates a new Writer. Writes to the returned Writer are compressed and written to w.

        It is the caller's responsibility to call Close on the Writer when done. Writes may be buffered and not flushed until Close.

        Example

        Code:

        var b bytes.Buffer
        
        w := zlib.NewWriter(&b)
        w.Write([]byte("hello, world\n"))
        w.Close()
        fmt.Println(b.Bytes())
        

        Output:

        [120 156 202 72 205 201 201 215 81 40 207 47 202 73 225 2 4 0 0 255 255 33 231 4 147]
        

        func NewWriterLevel

        func NewWriterLevel(w io.Writer, level int) (*Writer, error)

        NewWriterLevel is like NewWriter but specifies the compression level instead of assuming DefaultCompression.

        The compression level can be DefaultCompression, NoCompression, HuffmanOnly or any integer value between BestSpeed and BestCompression inclusive. The error returned will be nil if the level is valid.

        func NewWriterLevelDict

        func NewWriterLevelDict(w io.Writer, level int, dict []byte) (*Writer, error)

        NewWriterLevelDict is like NewWriterLevel but specifies a dictionary to compress with.

        The dictionary may be nil. If not, its contents should not be modified until the Writer is closed.

        func (*Writer) Close

        func (z *Writer) Close() error

        Close closes the Writer, flushing any unwritten data to the underlying io.Writer, but does not close the underlying io.Writer.

        func (*Writer) Flush

        func (z *Writer) Flush() error

        Flush flushes the Writer to its underlying io.Writer.

        func (*Writer) Reset

        func (z *Writer) Reset(w io.Writer)

        Reset clears the state of the Writer z such that it is equivalent to its initial state from NewWriterLevel or NewWriterLevelDict, but instead writing to w.

        func (*Writer) Write

        func (z *Writer) Write(p []byte) (n int, err error)

        Write writes a compressed form of p to the underlying io.Writer. The compressed bytes are not necessarily flushed until the Writer is closed or explicitly flushed.

        /src/container - Go Documentation Server
        ...

        Directory /src/container

        Name Synopsis
        ..
        heap Package heap provides heap operations for any type that implements heap.Interface.
        list Package list implements a doubly linked list.
        ring Package ring implements operations on circular lists.
        heap - Go Documentation Server
        ...

        Package heap

        import "container/heap"
        Overview
        Index
        Examples

        Overview ▾

        Package heap provides heap operations for any type that implements heap.Interface. A heap is a tree with the property that each node is the minimum-valued node in its subtree.

        The minimum element in the tree is the root, at index 0.

        A heap is a common way to implement a priority queue. To build a priority queue, implement the Heap interface with the (negative) priority as the ordering for the Less method, so Push adds items while Pop removes the highest-priority item from the queue. The Examples include such an implementation; the file example_pq_test.go has the complete source.

        Example (IntHeap)

        This example inserts several ints into an IntHeap, checks the minimum, and removes them in order of priority.

        Code:

        // This example demonstrates an integer heap built using the heap interface.
        package heap_test
        
        import (
            "container/heap"
            "fmt"
        )
        
        // An IntHeap is a min-heap of ints.
        type IntHeap []int
        
        func (h IntHeap) Len() int           { return len(h) }
        func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
        func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
        
        func (h *IntHeap) Push(x any) {
            // Push and Pop use pointer receivers because they modify the slice's length,
            // not just its contents.
            *h = append(*h, x.(int))
        }
        
        func (h *IntHeap) Pop() any {
            old := *h
            n := len(old)
            x := old[n-1]
            *h = old[0 : n-1]
            return x
        }
        
        // This example inserts several ints into an IntHeap, checks the minimum,
        // and removes them in order of priority.
        func Example_intHeap() {
            h := &IntHeap{2, 1, 5}
            heap.Init(h)
            heap.Push(h, 3)
            fmt.Printf("minimum: %d\n", (*h)[0])
            for h.Len() > 0 {
                fmt.Printf("%d ", heap.Pop(h))
            }
            // Output:
            // minimum: 1
            // 1 2 3 5
        }
        

        Example (PriorityQueue)

        This example creates a PriorityQueue with some items, adds and manipulates an item, and then removes the items in priority order.

        Code:

        // This example demonstrates a priority queue built using the heap interface.
        package heap_test
        
        import (
            "container/heap"
            "fmt"
        )
        
        // An Item is something we manage in a priority queue.
        type Item struct {
            value    string // The value of the item; arbitrary.
            priority int    // The priority of the item in the queue.
            // The index is needed by update and is maintained by the heap.Interface methods.
            index int // The index of the item in the heap.
        }
        
        // A PriorityQueue implements heap.Interface and holds Items.
        type PriorityQueue []*Item
        
        func (pq PriorityQueue) Len() int { return len(pq) }
        
        func (pq PriorityQueue) Less(i, j int) bool {
            // We want Pop to give us the highest, not lowest, priority so we use greater than here.
            return pq[i].priority > pq[j].priority
        }
        
        func (pq PriorityQueue) Swap(i, j int) {
            pq[i], pq[j] = pq[j], pq[i]
            pq[i].index = i
            pq[j].index = j
        }
        
        func (pq *PriorityQueue) Push(x any) {
            n := len(*pq)
            item := x.(*Item)
            item.index = n
            *pq = append(*pq, item)
        }
        
        func (pq *PriorityQueue) Pop() any {
            old := *pq
            n := len(old)
            item := old[n-1]
            old[n-1] = nil  // avoid memory leak
            item.index = -1 // for safety
            *pq = old[0 : n-1]
            return item
        }
        
        // update modifies the priority and value of an Item in the queue.
        func (pq *PriorityQueue) update(item *Item, value string, priority int) {
            item.value = value
            item.priority = priority
            heap.Fix(pq, item.index)
        }
        
        // This example creates a PriorityQueue with some items, adds and manipulates an item,
        // and then removes the items in priority order.
        func Example_priorityQueue() {
            // Some items and their priorities.
            items := map[string]int{
                "banana": 3, "apple": 2, "pear": 4,
            }
        
            // Create a priority queue, put the items in it, and
            // establish the priority queue (heap) invariants.
            pq := make(PriorityQueue, len(items))
            i := 0
            for value, priority := range items {
                pq[i] = &Item{
                    value:    value,
                    priority: priority,
                    index:    i,
                }
                i++
            }
            heap.Init(&pq)
        
            // Insert a new item and then modify its priority.
            item := &Item{
                value:    "orange",
                priority: 1,
            }
            heap.Push(&pq, item)
            pq.update(item, item.value, 5)
        
            // Take the items out; they arrive in decreasing priority order.
            for pq.Len() > 0 {
                item := heap.Pop(&pq).(*Item)
                fmt.Printf("%.2d:%s ", item.priority, item.value)
            }
            // Output:
            // 05:orange 04:pear 03:banana 02:apple
        }
        

        func Fix

        func Fix(h Interface, i int)

        Fix re-establishes the heap ordering after the element at index i has changed its value. Changing the value of the element at index i and then calling Fix is equivalent to, but less expensive than, calling Remove(h, i) followed by a Push of the new value. The complexity is O(log n) where n = h.Len().

        func Init

        func Init(h Interface)

        Init establishes the heap invariants required by the other routines in this package. Init is idempotent with respect to the heap invariants and may be called whenever the heap invariants may have been invalidated. The complexity is O(n) where n = h.Len().

        func Pop

        func Pop(h Interface) any

        Pop removes and returns the minimum element (according to Less) from the heap. The complexity is O(log n) where n = h.Len(). Pop is equivalent to Remove(h, 0).

        func Push

        func Push(h Interface, x any)

        Push pushes the element x onto the heap. The complexity is O(log n) where n = h.Len().

        func Remove

        func Remove(h Interface, i int) any

        Remove removes and returns the element at index i from the heap. The complexity is O(log n) where n = h.Len().

        type Interface

        The Interface type describes the requirements for a type using the routines in this package. Any type that implements it may be used as a min-heap with the following invariants (established after Init has been called or if the data is empty or sorted):

        !h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len()
        

        Note that Push and Pop in this interface are for package heap's implementation to call. To add and remove things from the heap, use heap.Push and heap.Pop.

        type Interface interface {
            sort.Interface
            Push(x any) // add x as element Len()
            Pop() any   // remove and return element Len() - 1.
        }
        list - Go Documentation Server
        ...

        Package list

        import "container/list"
        Overview
        Index
        Examples

        Overview ▾

        Package list implements a doubly linked list.

        To iterate over a list (where l is a *List):

        for e := l.Front(); e != nil; e = e.Next() {
        	// do something with e.Value
        }
        

        Example

        Code:

        // Create a new list and put some numbers in it.
        l := list.New()
        e4 := l.PushBack(4)
        e1 := l.PushFront(1)
        l.InsertBefore(3, e4)
        l.InsertAfter(2, e1)
        
        // Iterate through list and print its contents.
        for e := l.Front(); e != nil; e = e.Next() {
            fmt.Println(e.Value)
        }
        
        

        Output:

        1
        2
        3
        4
        

        type Element

        Element is an element of a linked list.

        type Element struct {
        
            // The value stored with this element.
            Value any
            // contains filtered or unexported fields
        }
        

        func (*Element) Next

        func (e *Element) Next() *Element

        Next returns the next list element or nil.

        func (*Element) Prev

        func (e *Element) Prev() *Element

        Prev returns the previous list element or nil.

        type List

        List represents a doubly linked list. The zero value for List is an empty list ready to use.

        type List struct {
            // contains filtered or unexported fields
        }
        

        func New

        func New() *List

        New returns an initialized list.

        func (*List) Back

        func (l *List) Back() *Element

        Back returns the last element of list l or nil if the list is empty.

        func (*List) Front

        func (l *List) Front() *Element

        Front returns the first element of list l or nil if the list is empty.

        func (*List) Init

        func (l *List) Init() *List

        Init initializes or clears list l.

        func (*List) InsertAfter

        func (l *List) InsertAfter(v any, mark *Element) *Element

        InsertAfter inserts a new element e with value v immediately after mark and returns e. If mark is not an element of l, the list is not modified. The mark must not be nil.

        func (*List) InsertBefore

        func (l *List) InsertBefore(v any, mark *Element) *Element

        InsertBefore inserts a new element e with value v immediately before mark and returns e. If mark is not an element of l, the list is not modified. The mark must not be nil.

        func (*List) Len

        func (l *List) Len() int

        Len returns the number of elements of list l. The complexity is O(1).

        func (*List) MoveAfter

        func (l *List) MoveAfter(e, mark *Element)

        MoveAfter moves element e to its new position after mark. If e or mark is not an element of l, or e == mark, the list is not modified. The element and mark must not be nil.

        func (*List) MoveBefore

        func (l *List) MoveBefore(e, mark *Element)

        MoveBefore moves element e to its new position before mark. If e or mark is not an element of l, or e == mark, the list is not modified. The element and mark must not be nil.

        func (*List) MoveToBack

        func (l *List) MoveToBack(e *Element)

        MoveToBack moves element e to the back of list l. If e is not an element of l, the list is not modified. The element must not be nil.

        func (*List) MoveToFront

        func (l *List) MoveToFront(e *Element)

        MoveToFront moves element e to the front of list l. If e is not an element of l, the list is not modified. The element must not be nil.

        func (*List) PushBack

        func (l *List) PushBack(v any) *Element

        PushBack inserts a new element e with value v at the back of list l and returns e.

        func (*List) PushBackList

        func (l *List) PushBackList(other *List)

        PushBackList inserts a copy of another list at the back of list l. The lists l and other may be the same. They must not be nil.

        func (*List) PushFront

        func (l *List) PushFront(v any) *Element

        PushFront inserts a new element e with value v at the front of list l and returns e.

        func (*List) PushFrontList

        func (l *List) PushFrontList(other *List)

        PushFrontList inserts a copy of another list at the front of list l. The lists l and other may be the same. They must not be nil.

        func (*List) Remove

        func (l *List) Remove(e *Element) any

        Remove removes e from l if e is an element of list l. It returns the element value e.Value. The element must not be nil.

        ring - Go Documentation Server
        ...

        Package ring

        import "container/ring"
        Overview
        Index
        Examples

        Overview ▾

        Package ring implements operations on circular lists.

        type Ring

        A Ring is an element of a circular list, or ring. Rings do not have a beginning or end; a pointer to any ring element serves as reference to the entire ring. Empty rings are represented as nil Ring pointers. The zero value for a Ring is a one-element ring with a nil Value.

        type Ring struct {
            Value any // for use by client; untouched by this library
            // contains filtered or unexported fields
        }
        

        func New

        func New(n int) *Ring

        New creates a ring of n elements.

        func (*Ring) Do

        func (r *Ring) Do(f func(any))

        Do calls function f on each element of the ring, in forward order. The behavior of Do is undefined if f changes *r.

        Example

        Code:

        // Create a new ring of size 5
        r := ring.New(5)
        
        // Get the length of the ring
        n := r.Len()
        
        // Initialize the ring with some integer values
        for i := 0; i < n; i++ {
            r.Value = i
            r = r.Next()
        }
        
        // Iterate through the ring and print its contents
        r.Do(func(p any) {
            fmt.Println(p.(int))
        })
        
        

        Output:

        0
        1
        2
        3
        4
        

        func (*Ring) Len

        func (r *Ring) Len() int

        Len computes the number of elements in ring r. It executes in time proportional to the number of elements.

        Example

        Code:

        // Create a new ring of size 4
        r := ring.New(4)
        
        // Print out its length
        fmt.Println(r.Len())
        
        

        Output:

        4
        
        func (r *Ring) Link(s *Ring) *Ring

        Link connects ring r with ring s such that r.Next() becomes s and returns the original value for r.Next(). r must not be empty.

        If r and s point to the same ring, linking them removes the elements between r and s from the ring. The removed elements form a subring and the result is a reference to that subring (if no elements were removed, the result is still the original value for r.Next(), and not nil).

        If r and s point to different rings, linking them creates a single ring with the elements of s inserted after r. The result points to the element following the last element of s after insertion.

        func (*Ring) Move

        func (r *Ring) Move(n int) *Ring

        Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0) in the ring and returns that ring element. r must not be empty.

        Example

        Code:

        // Create a new ring of size 5
        r := ring.New(5)
        
        // Get the length of the ring
        n := r.Len()
        
        // Initialize the ring with some integer values
        for i := 0; i < n; i++ {
            r.Value = i
            r = r.Next()
        }
        
        // Move the pointer forward by three steps
        r = r.Move(3)
        
        // Iterate through the ring and print its contents
        r.Do(func(p any) {
            fmt.Println(p.(int))
        })
        
        

        Output:

        3
        4
        0
        1
        2
        

        func (*Ring) Next

        func (r *Ring) Next() *Ring

        Next returns the next ring element. r must not be empty.

        Example

        Code:

        // Create a new ring of size 5
        r := ring.New(5)
        
        // Get the length of the ring
        n := r.Len()
        
        // Initialize the ring with some integer values
        for i := 0; i < n; i++ {
            r.Value = i
            r = r.Next()
        }
        
        // Iterate through the ring and print its contents
        for j := 0; j < n; j++ {
            fmt.Println(r.Value)
            r = r.Next()
        }
        
        

        Output:

        0
        1
        2
        3
        4
        

        func (*Ring) Prev

        func (r *Ring) Prev() *Ring

        Prev returns the previous ring element. r must not be empty.

        Example

        Code:

        // Create a new ring of size 5
        r := ring.New(5)
        
        // Get the length of the ring
        n := r.Len()
        
        // Initialize the ring with some integer values
        for i := 0; i < n; i++ {
            r.Value = i
            r = r.Next()
        }
        
        // Iterate through the ring backwards and print its contents
        for j := 0; j < n; j++ {
            r = r.Prev()
            fmt.Println(r.Value)
        }
        
        

        Output:

        4
        3
        2
        1
        0
        
        func (r *Ring) Unlink(n int) *Ring

        Unlink removes n % r.Len() elements from the ring r, starting at r.Next(). If n % r.Len() == 0, r remains unchanged. The result is the removed subring. r must not be empty.

        context - Go Documentation Server
        ...

        Package context

        import "context"
        Overview
        Index
        Examples

        Overview ▾

        Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.

        Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context. The chain of function calls between them must propagate the Context, optionally replacing it with a derived Context created using WithCancel, WithDeadline, WithTimeout, or WithValue. When a Context is canceled, all Contexts derived from it are also canceled.

        The WithCancel, WithDeadline, and WithTimeout functions take a Context (the parent) and return a derived Context (the child) and a CancelFunc. Calling the CancelFunc cancels the child and its children, removes the parent's reference to the child, and stops any associated timers. Failing to call the CancelFunc leaks the child and its children until the parent is canceled or the timer fires. The go vet tool checks that CancelFuncs are used on all control-flow paths.

        The WithCancelCause function returns a CancelCauseFunc, which takes an error and records it as the cancellation cause. Calling Cause on the canceled context or any of its children retrieves the cause. If no cause is specified, Cause(ctx) returns the same value as ctx.Err().

        Programs that use Contexts should follow these rules to keep interfaces consistent across packages and enable static analysis tools to check context propagation:

        Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx:

        func DoSomething(ctx context.Context, arg Arg) error {
        	// ... use ctx ...
        }
        

        Do not pass a nil Context, even if a function permits it. Pass context.TODO if you are unsure about which Context to use.

        Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.

        The same Context may be passed to functions running in different goroutines; Contexts are safe for simultaneous use by multiple goroutines.

        See https://blog.golang.org/context for example code for a server that uses Contexts.

        Variables

        Canceled is the error returned by [Context.Err] when the context is canceled.

        var Canceled = errors.New("context canceled")

        DeadlineExceeded is the error returned by [Context.Err] when the context's deadline passes.

        var DeadlineExceeded error = deadlineExceededError{}

        func AfterFunc

        func AfterFunc(ctx Context, f func()) (stop func() bool)

        AfterFunc arranges to call f in its own goroutine after ctx is done (cancelled or timed out). If ctx is already done, AfterFunc calls f immediately in its own goroutine.

        Multiple calls to AfterFunc on a context operate independently; one does not replace another.

        Calling the returned stop function stops the association of ctx with f. It returns true if the call stopped f from being run. If stop returns false, either the context is done and f has been started in its own goroutine; or f was already stopped. The stop function does not wait for f to complete before returning. If the caller needs to know whether f is completed, it must coordinate with f explicitly.

        If ctx has a "AfterFunc(func()) func() bool" method, AfterFunc will use it to schedule the call.

        Example (Cond)

        This example uses AfterFunc to define a function which waits on a sync.Cond, stopping the wait when a context is canceled.

        Code:

        waitOnCond := func(ctx context.Context, cond *sync.Cond, conditionMet func() bool) error {
            stopf := context.AfterFunc(ctx, func() {
                // We need to acquire cond.L here to be sure that the Broadcast
                // below won't occur before the call to Wait, which would result
                // in a missed signal (and deadlock).
                cond.L.Lock()
                defer cond.L.Unlock()
        
                // If multiple goroutines are waiting on cond simultaneously,
                // we need to make sure we wake up exactly this one.
                // That means that we need to Broadcast to all of the goroutines,
                // which will wake them all up.
                //
                // If there are N concurrent calls to waitOnCond, each of the goroutines
                // will spuriously wake up O(N) other goroutines that aren't ready yet,
                // so this will cause the overall CPU cost to be O(N²).
                cond.Broadcast()
            })
            defer stopf()
        
            // Since the wakeups are using Broadcast instead of Signal, this call to
            // Wait may unblock due to some other goroutine's context becoming done,
            // so to be sure that ctx is actually done we need to check it in a loop.
            for !conditionMet() {
                cond.Wait()
                if ctx.Err() != nil {
                    return ctx.Err()
                }
            }
        
            return nil
        }
        
        cond := sync.NewCond(new(sync.Mutex))
        
        var wg sync.WaitGroup
        for i := 0; i < 4; i++ {
            wg.Add(1)
            go func() {
                defer wg.Done()
        
                ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
                defer cancel()
        
                cond.L.Lock()
                defer cond.L.Unlock()
        
                err := waitOnCond(ctx, cond, func() bool { return false })
                fmt.Println(err)
            }()
        }
        wg.Wait()
        
        

        Output:

        context deadline exceeded
        context deadline exceeded
        context deadline exceeded
        context deadline exceeded
        

        Example (Connection)

        This example uses AfterFunc to define a function which reads from a net.Conn, stopping the read when a context is canceled.

        Code:

        readFromConn := func(ctx context.Context, conn net.Conn, b []byte) (n int, err error) {
            stopc := make(chan struct{})
            stop := context.AfterFunc(ctx, func() {
                conn.SetReadDeadline(time.Now())
                close(stopc)
            })
            n, err = conn.Read(b)
            if !stop() {
                // The AfterFunc was started.
                // Wait for it to complete, and reset the Conn's deadline.
                <-stopc
                conn.SetReadDeadline(time.Time{})
                return n, ctx.Err()
            }
            return n, err
        }
        
        listener, err := net.Listen("tcp", ":0")
        if err != nil {
            fmt.Println(err)
            return
        }
        defer listener.Close()
        
        conn, err := net.Dial(listener.Addr().Network(), listener.Addr().String())
        if err != nil {
            fmt.Println(err)
            return
        }
        defer conn.Close()
        
        ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
        defer cancel()
        
        b := make([]byte, 1024)
        _, err = readFromConn(ctx, conn, b)
        fmt.Println(err)
        
        

        Output:

        context deadline exceeded
        

        Example (Merge)

        This example uses AfterFunc to define a function which combines the cancellation signals of two Contexts.

        Code:

        // mergeCancel returns a context that contains the values of ctx,
        // and which is canceled when either ctx or cancelCtx is canceled.
        mergeCancel := func(ctx, cancelCtx context.Context) (context.Context, context.CancelFunc) {
            ctx, cancel := context.WithCancelCause(ctx)
            stop := context.AfterFunc(cancelCtx, func() {
                cancel(context.Cause(cancelCtx))
            })
            return ctx, func() {
                stop()
                cancel(context.Canceled)
            }
        }
        
        ctx1, cancel1 := context.WithCancelCause(context.Background())
        defer cancel1(errors.New("ctx1 canceled"))
        
        ctx2, cancel2 := context.WithCancelCause(context.Background())
        
        mergedCtx, mergedCancel := mergeCancel(ctx1, ctx2)
        defer mergedCancel()
        
        cancel2(errors.New("ctx2 canceled"))
        <-mergedCtx.Done()
        fmt.Println(context.Cause(mergedCtx))
        
        

        Output:

        ctx2 canceled
        

        func Cause

        func Cause(c Context) error

        Cause returns a non-nil error explaining why c was canceled. The first cancellation of c or one of its parents sets the cause. If that cancellation happened via a call to CancelCauseFunc(err), then Cause returns err. Otherwise Cause(c) returns the same value as c.Err(). Cause returns nil if c has not been canceled yet.

        func WithCancel

        func WithCancel(parent Context) (ctx Context, cancel CancelFunc)

        WithCancel returns a copy of parent with a new Done channel. The returned context's Done channel is closed when the returned cancel function is called or when the parent context's Done channel is closed, whichever happens first.

        Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.

        Example

        This example demonstrates the use of a cancelable context to prevent a goroutine leak. By the end of the example function, the goroutine started by gen will return without leaking.

        Code:

        // gen generates integers in a separate goroutine and
        // sends them to the returned channel.
        // The callers of gen need to cancel the context once
        // they are done consuming generated integers not to leak
        // the internal goroutine started by gen.
        gen := func(ctx context.Context) <-chan int {
            dst := make(chan int)
            n := 1
            go func() {
                for {
                    select {
                    case <-ctx.Done():
                        return // returning not to leak the goroutine
                    case dst <- n:
                        n++
                    }
                }
            }()
            return dst
        }
        
        ctx, cancel := context.WithCancel(context.Background())
        defer cancel() // cancel when we are finished consuming integers
        
        for n := range gen(ctx) {
            fmt.Println(n)
            if n == 5 {
                break
            }
        }
        

        Output:

        1
        2
        3
        4
        5
        

        func WithCancelCause

        func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)

        WithCancelCause behaves like WithCancel but returns a CancelCauseFunc instead of a CancelFunc. Calling cancel with a non-nil error (the "cause") records that error in ctx; it can then be retrieved using Cause(ctx). Calling cancel with nil sets the cause to Canceled.

        Example use:

        ctx, cancel := context.WithCancelCause(parent)
        cancel(myError)
        ctx.Err() // returns context.Canceled
        context.Cause(ctx) // returns myError
        

        func WithDeadline

        func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)

        WithDeadline returns a copy of the parent context with the deadline adjusted to be no later than d. If the parent's deadline is already earlier than d, WithDeadline(parent, d) is semantically equivalent to parent. The returned [Context.Done] channel is closed when the deadline expires, when the returned cancel function is called, or when the parent context's Done channel is closed, whichever happens first.

        Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.

        Example

        This example passes a context with an arbitrary deadline to tell a blocking function that it should abandon its work as soon as it gets to it.

        Code:

        d := time.Now().Add(shortDuration)
        ctx, cancel := context.WithDeadline(context.Background(), d)
        
        // Even though ctx will be expired, it is good practice to call its
        // cancellation function in any case. Failure to do so may keep the
        // context and its parent alive longer than necessary.
        defer cancel()
        
        select {
        case <-neverReady:
            fmt.Println("ready")
        case <-ctx.Done():
            fmt.Println(ctx.Err())
        }
        
        

        Output:

        context deadline exceeded
        

        func WithDeadlineCause

        func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc)

        WithDeadlineCause behaves like WithDeadline but also sets the cause of the returned Context when the deadline is exceeded. The returned CancelFunc does not set the cause.

        func WithTimeout

        func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

        WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).

        Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete:

        func slowOperationWithTimeout(ctx context.Context) (Result, error) {
        	ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
        	defer cancel()  // releases resources if slowOperation completes before timeout elapses
        	return slowOperation(ctx)
        }
        

        Example

        This example passes a context with a timeout to tell a blocking function that it should abandon its work after the timeout elapses.

        Code:

        // Pass a context with a timeout to tell a blocking function that it
        // should abandon its work after the timeout elapses.
        ctx, cancel := context.WithTimeout(context.Background(), shortDuration)
        defer cancel()
        
        select {
        case <-neverReady:
            fmt.Println("ready")
        case <-ctx.Done():
            fmt.Println(ctx.Err()) // prints "context deadline exceeded"
        }
        
        

        Output:

        context deadline exceeded
        

        func WithTimeoutCause

        func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)

        WithTimeoutCause behaves like WithTimeout but also sets the cause of the returned Context when the timeout expires. The returned CancelFunc does not set the cause.

        type CancelCauseFunc

        A CancelCauseFunc behaves like a CancelFunc but additionally sets the cancellation cause. This cause can be retrieved by calling Cause on the canceled Context or on any of its derived Contexts.

        If the context has already been canceled, CancelCauseFunc does not set the cause. For example, if childContext is derived from parentContext:

        • if parentContext is canceled with cause1 before childContext is canceled with cause2, then Cause(parentContext) == Cause(childContext) == cause1
        • if childContext is canceled with cause2 before parentContext is canceled with cause1, then Cause(parentContext) == cause1 and Cause(childContext) == cause2
        type CancelCauseFunc func(cause error)

        type CancelFunc

        A CancelFunc tells an operation to abandon its work. A CancelFunc does not wait for the work to stop. A CancelFunc may be called by multiple goroutines simultaneously. After the first call, subsequent calls to a CancelFunc do nothing.

        type CancelFunc func()

        type Context

        A Context carries a deadline, a cancellation signal, and other values across API boundaries.

        Context's methods may be called by multiple goroutines simultaneously.

        type Context interface {
            // Deadline returns the time when work done on behalf of this context
            // should be canceled. Deadline returns ok==false when no deadline is
            // set. Successive calls to Deadline return the same results.
            Deadline() (deadline time.Time, ok bool)
        
            // Done returns a channel that's closed when work done on behalf of this
            // context should be canceled. Done may return nil if this context can
            // never be canceled. Successive calls to Done return the same value.
            // The close of the Done channel may happen asynchronously,
            // after the cancel function returns.
            //
            // WithCancel arranges for Done to be closed when cancel is called;
            // WithDeadline arranges for Done to be closed when the deadline
            // expires; WithTimeout arranges for Done to be closed when the timeout
            // elapses.
            //
            // Done is provided for use in select statements:
            //
            //  // Stream generates values with DoSomething and sends them to out
            //  // until DoSomething returns an error or ctx.Done is closed.
            //  func Stream(ctx context.Context, out chan<- Value) error {
            //  	for {
            //  		v, err := DoSomething(ctx)
            //  		if err != nil {
            //  			return err
            //  		}
            //  		select {
            //  		case <-ctx.Done():
            //  			return ctx.Err()
            //  		case out <- v:
            //  		}
            //  	}
            //  }
            //
            // See https://blog.golang.org/pipelines for more examples of how to use
            // a Done channel for cancellation.
            Done() <-chan struct{}
        
            // If Done is not yet closed, Err returns nil.
            // If Done is closed, Err returns a non-nil error explaining why:
            // Canceled if the context was canceled
            // or DeadlineExceeded if the context's deadline passed.
            // After Err returns a non-nil error, successive calls to Err return the same error.
            Err() error
        
            // Value returns the value associated with this context for key, or nil
            // if no value is associated with key. Successive calls to Value with
            // the same key returns the same result.
            //
            // Use context values only for request-scoped data that transits
            // processes and API boundaries, not for passing optional parameters to
            // functions.
            //
            // A key identifies a specific value in a Context. Functions that wish
            // to store values in Context typically allocate a key in a global
            // variable then use that key as the argument to context.WithValue and
            // Context.Value. A key can be any type that supports equality;
            // packages should define keys as an unexported type to avoid
            // collisions.
            //
            // Packages that define a Context key should provide type-safe accessors
            // for the values stored using that key:
            //
            // 	// Package user defines a User type that's stored in Contexts.
            // 	package user
            //
            // 	import "context"
            //
            // 	// User is the type of value stored in the Contexts.
            // 	type User struct {...}
            //
            // 	// key is an unexported type for keys defined in this package.
            // 	// This prevents collisions with keys defined in other packages.
            // 	type key int
            //
            // 	// userKey is the key for user.User values in Contexts. It is
            // 	// unexported; clients use user.NewContext and user.FromContext
            // 	// instead of using this key directly.
            // 	var userKey key
            //
            // 	// NewContext returns a new Context that carries value u.
            // 	func NewContext(ctx context.Context, u *User) context.Context {
            // 		return context.WithValue(ctx, userKey, u)
            // 	}
            //
            // 	// FromContext returns the User value stored in ctx, if any.
            // 	func FromContext(ctx context.Context) (*User, bool) {
            // 		u, ok := ctx.Value(userKey).(*User)
            // 		return u, ok
            // 	}
            Value(key any) any
        }

        func Background

        func Background() Context

        Background returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline. It is typically used by the main function, initialization, and tests, and as the top-level Context for incoming requests.

        func TODO

        func TODO() Context

        TODO returns a non-nil, empty Context. Code should use context.TODO when it's unclear which Context to use or it is not yet available (because the surrounding function has not yet been extended to accept a Context parameter).

        func WithValue

        func WithValue(parent Context, key, val any) Context

        WithValue returns a copy of parent in which the value associated with key is val.

        Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.

        The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys. To avoid allocating when assigning to an interface{}, context keys often have concrete type struct{}. Alternatively, exported context key variables' static type should be a pointer or interface.

        Example

        This example demonstrates how a value can be passed to the context and also how to retrieve it if it exists.

        Code:

        type favContextKey string
        
        f := func(ctx context.Context, k favContextKey) {
            if v := ctx.Value(k); v != nil {
                fmt.Println("found value:", v)
                return
            }
            fmt.Println("key not found:", k)
        }
        
        k := favContextKey("language")
        ctx := context.WithValue(context.Background(), k, "Go")
        
        f(ctx, k)
        f(ctx, favContextKey("color"))
        
        

        Output:

        found value: Go
        key not found: color
        

        func WithoutCancel

        func WithoutCancel(parent Context) Context

        WithoutCancel returns a copy of parent that is not canceled when parent is canceled. The returned context returns no Deadline or Err, and its Done channel is nil. Calling Cause on the returned context returns nil.

        crypto - Go Documentation Server
        ...

        Package crypto

        import "crypto"
        Overview
        Index
        Subdirectories

        Overview ▾

        Package crypto collects common cryptographic constants.

        func RegisterHash

        func RegisterHash(h Hash, f func() hash.Hash)

        RegisterHash registers a function that returns a new instance of the given hash function. This is intended to be called from the init function in packages that implement hash functions.

        type Decrypter

        Decrypter is an interface for an opaque private key that can be used for asymmetric decryption operations. An example would be an RSA key kept in a hardware module.

        type Decrypter interface {
            // Public returns the public key corresponding to the opaque,
            // private key.
            Public() PublicKey
        
            // Decrypt decrypts msg. The opts argument should be appropriate for
            // the primitive used. See the documentation in each implementation for
            // details.
            Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error)
        }

        type DecrypterOpts

        type DecrypterOpts any

        type Hash

        Hash identifies a cryptographic hash function that is implemented in another package.

        type Hash uint
        const (
            MD4         Hash = 1 + iota // import golang.org/x/crypto/md4
            MD5                         // import crypto/md5
            SHA1                        // import crypto/sha1
            SHA224                      // import crypto/sha256
            SHA256                      // import crypto/sha256
            SHA384                      // import crypto/sha512
            SHA512                      // import crypto/sha512
            MD5SHA1                     // no implementation; MD5+SHA1 used for TLS RSA
            RIPEMD160                   // import golang.org/x/crypto/ripemd160
            SHA3_224                    // import golang.org/x/crypto/sha3
            SHA3_256                    // import golang.org/x/crypto/sha3
            SHA3_384                    // import golang.org/x/crypto/sha3
            SHA3_512                    // import golang.org/x/crypto/sha3
            SHA512_224                  // import crypto/sha512
            SHA512_256                  // import crypto/sha512
            BLAKE2s_256                 // import golang.org/x/crypto/blake2s
            BLAKE2b_256                 // import golang.org/x/crypto/blake2b
            BLAKE2b_384                 // import golang.org/x/crypto/blake2b
            BLAKE2b_512                 // import golang.org/x/crypto/blake2b
        
        )

        func (Hash) Available

        func (h Hash) Available() bool

        Available reports whether the given hash function is linked into the binary.

        func (Hash) HashFunc

        func (h Hash) HashFunc() Hash

        HashFunc simply returns the value of h so that Hash implements SignerOpts.

        func (Hash) New

        func (h Hash) New() hash.Hash

        New returns a new hash.Hash calculating the given hash function. New panics if the hash function is not linked into the binary.

        func (Hash) Size

        func (h Hash) Size() int

        Size returns the length, in bytes, of a digest resulting from the given hash function. It doesn't require that the hash function in question be linked into the program.

        func (Hash) String

        func (h Hash) String() string

        type PrivateKey

        PrivateKey represents a private key using an unspecified algorithm.

        Although this type is an empty interface for backwards compatibility reasons, all private key types in the standard library implement the following interface

        interface{
            Public() crypto.PublicKey
            Equal(x crypto.PrivateKey) bool
        }
        

        as well as purpose-specific interfaces such as Signer and Decrypter, which can be used for increased type safety within applications.

        type PrivateKey any

        type PublicKey

        PublicKey represents a public key using an unspecified algorithm.

        Although this type is an empty interface for backwards compatibility reasons, all public key types in the standard library implement the following interface

        interface{
            Equal(x crypto.PublicKey) bool
        }
        

        which can be used for increased type safety within applications.

        type PublicKey any

        type Signer

        Signer is an interface for an opaque private key that can be used for signing operations. For example, an RSA key kept in a hardware module.

        type Signer interface {
            // Public returns the public key corresponding to the opaque,
            // private key.
            Public() PublicKey
        
            // Sign signs digest with the private key, possibly using entropy from
            // rand. For an RSA key, the resulting signature should be either a
            // PKCS #1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA
            // key, it should be a DER-serialised, ASN.1 signature structure.
            //
            // Hash implements the SignerOpts interface and, in most cases, one can
            // simply pass in the hash function used as opts. Sign may also attempt
            // to type assert opts to other types in order to obtain algorithm
            // specific values. See the documentation in each package for details.
            //
            // Note that when a signature of a hash of a larger message is needed,
            // the caller is responsible for hashing the larger message and passing
            // the hash (as digest) and the hash function (as opts) to Sign.
            Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error)
        }

        type SignerOpts

        SignerOpts contains options for signing with a Signer.

        type SignerOpts interface {
            // HashFunc returns an identifier for the hash function used to produce
            // the message passed to Signer.Sign, or else zero to indicate that no
            // hashing was done.
            HashFunc() Hash
        }

        Subdirectories

        Name Synopsis
        ..
        aes Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.
        boring Package boring exposes functions that are only available when building with Go+BoringCrypto.
        cipher Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations.
        des Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3.
        dsa Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.
        ecdh Package ecdh implements Elliptic Curve Diffie-Hellman over NIST curves and Curve25519.
        ecdsa Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-4 and SEC 1, Version 2.0.
        ed25519 Package ed25519 implements the Ed25519 signature algorithm.
        elliptic Package elliptic implements the standard NIST P-224, P-256, P-384, and P-521 elliptic curves over prime fields.
        hmac Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198.
        md5 Package md5 implements the MD5 hash algorithm as defined in RFC 1321.
        rand Package rand implements a cryptographically secure random number generator.
        rc4 Package rc4 implements RC4 encryption, as defined in Bruce Schneier's Applied Cryptography.
        rsa Package rsa implements RSA encryption as specified in PKCS #1 and RFC 8017.
        sha1 Package sha1 implements the SHA-1 hash algorithm as defined in RFC 3174.
        sha256 Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.
        sha512 Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.
        subtle Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.
        tls Package tls partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.
        fipsonly Package fipsonly restricts all TLS configuration to FIPS-approved settings.
        x509 Package x509 implements a subset of the X.509 standard.
        pkix Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.
        aes - Go Documentation Server
        ...

        Package aes

        import "crypto/aes"
        Overview
        Index

        Overview ▾

        Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.

        The AES operations in this package are not implemented using constant-time algorithms. An exception is when running on systems with enabled hardware support for AES that makes these operations constant-time. Examples include amd64 systems using AES-NI extensions and s390x systems using Message-Security-Assist extensions. On such systems, when the result of NewCipher is passed to cipher.NewGCM, the GHASH operation used by GCM is also constant-time.

        Constants

        The AES block size in bytes.

        const BlockSize = 16

        func NewCipher

        func NewCipher(key []byte) (cipher.Block, error)

        NewCipher creates and returns a new cipher.Block. The key argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

        type KeySizeError

        type KeySizeError int

        func (KeySizeError) Error

        func (k KeySizeError) Error() string
        boring - Go Documentation Server
        ...

        Command boring

        Package boring exposes functions that are only available when building with Go+BoringCrypto. This package is available on all targets as long as the Go+BoringCrypto toolchain is used. Use the Enabled function to determine whether the BoringCrypto core is actually in use.

        Any time the Go+BoringCrypto toolchain is used, the "boringcrypto" build tag is satisfied, so that applications can tag files that use this package.

        cipher - Go Documentation Server
        ...

        Package cipher

        import "crypto/cipher"
        Overview
        Index
        Examples

        Overview ▾

        Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations. See https://csrc.nist.gov/groups/ST/toolkit/BCM/current_modes.html and NIST Special Publication 800-38A.

        type AEAD

        AEAD is a cipher mode providing authenticated encryption with associated data. For a description of the methodology, see https://en.wikipedia.org/wiki/Authenticated_encryption.

        type AEAD interface {
            // NonceSize returns the size of the nonce that must be passed to Seal
            // and Open.
            NonceSize() int
        
            // Overhead returns the maximum difference between the lengths of a
            // plaintext and its ciphertext.
            Overhead() int
        
            // Seal encrypts and authenticates plaintext, authenticates the
            // additional data and appends the result to dst, returning the updated
            // slice. The nonce must be NonceSize() bytes long and unique for all
            // time, for a given key.
            //
            // To reuse plaintext's storage for the encrypted output, use plaintext[:0]
            // as dst. Otherwise, the remaining capacity of dst must not overlap plaintext.
            Seal(dst, nonce, plaintext, additionalData []byte) []byte
        
            // Open decrypts and authenticates ciphertext, authenticates the
            // additional data and, if successful, appends the resulting plaintext
            // to dst, returning the updated slice. The nonce must be NonceSize()
            // bytes long and both it and the additional data must match the
            // value passed to Seal.
            //
            // To reuse ciphertext's storage for the decrypted output, use ciphertext[:0]
            // as dst. Otherwise, the remaining capacity of dst must not overlap plaintext.
            //
            // Even if the function fails, the contents of dst, up to its capacity,
            // may be overwritten.
            Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
        }

        func NewGCM

        func NewGCM(cipher Block) (AEAD, error)

        NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode with the standard nonce length.

        In general, the GHASH operation performed by this implementation of GCM is not constant-time. An exception is when the underlying Block was created by aes.NewCipher on systems with hardware support for AES. See the crypto/aes package documentation for details.

        Example (Decrypt)

        Code:

        // Load your secret key from a safe place and reuse it across multiple
        // Seal/Open calls. (Obviously don't use this example key for anything
        // real.) If you want to convert a passphrase to a key, use a suitable
        // package like bcrypt or scrypt.
        // When decoded the key should be 16 bytes (AES-128) or 32 (AES-256).
        key, _ := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
        ciphertext, _ := hex.DecodeString("c3aaa29f002ca75870806e44086700f62ce4d43e902b3888e23ceff797a7a471")
        nonce, _ := hex.DecodeString("64a9433eae7ccceee2fc0eda")
        
        block, err := aes.NewCipher(key)
        if err != nil {
            panic(err.Error())
        }
        
        aesgcm, err := cipher.NewGCM(block)
        if err != nil {
            panic(err.Error())
        }
        
        plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
        if err != nil {
            panic(err.Error())
        }
        
        fmt.Printf("%s\n", plaintext)
        

        Output:

        exampleplaintext
        

        Example (Encrypt)

        Code:

        // Load your secret key from a safe place and reuse it across multiple
        // Seal/Open calls. (Obviously don't use this example key for anything
        // real.) If you want to convert a passphrase to a key, use a suitable
        // package like bcrypt or scrypt.
        // When decoded the key should be 16 bytes (AES-128) or 32 (AES-256).
        key, _ := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
        plaintext := []byte("exampleplaintext")
        
        block, err := aes.NewCipher(key)
        if err != nil {
            panic(err.Error())
        }
        
        // Never use more than 2^32 random nonces with a given key because of the risk of a repeat.
        nonce := make([]byte, 12)
        if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
            panic(err.Error())
        }
        
        aesgcm, err := cipher.NewGCM(block)
        if err != nil {
            panic(err.Error())
        }
        
        ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
        fmt.Printf("%x\n", ciphertext)
        

        func NewGCMWithNonceSize

        func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error)

        NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois Counter Mode, which accepts nonces of the given length. The length must not be zero.

        Only use this function if you require compatibility with an existing cryptosystem that uses non-standard nonce lengths. All other users should use NewGCM, which is faster and more resistant to misuse.

        func NewGCMWithTagSize

        func NewGCMWithTagSize(cipher Block, tagSize int) (AEAD, error)

        NewGCMWithTagSize returns the given 128-bit, block cipher wrapped in Galois Counter Mode, which generates tags with the given length.

        Tag sizes between 12 and 16 bytes are allowed.

        Only use this function if you require compatibility with an existing cryptosystem that uses non-standard tag lengths. All other users should use NewGCM, which is more resistant to misuse.

        type Block

        A Block represents an implementation of block cipher using a given key. It provides the capability to encrypt or decrypt individual blocks. The mode implementations extend that capability to streams of blocks.

        type Block interface {
            // BlockSize returns the cipher's block size.
            BlockSize() int
        
            // Encrypt encrypts the first block in src into dst.
            // Dst and src must overlap entirely or not at all.
            Encrypt(dst, src []byte)
        
            // Decrypt decrypts the first block in src into dst.
            // Dst and src must overlap entirely or not at all.
            Decrypt(dst, src []byte)
        }

        type BlockMode

        A BlockMode represents a block cipher running in a block-based mode (CBC, ECB etc).

        type BlockMode interface {
            // BlockSize returns the mode's block size.
            BlockSize() int
        
            // CryptBlocks encrypts or decrypts a number of blocks. The length of
            // src must be a multiple of the block size. Dst and src must overlap
            // entirely or not at all.
            //
            // If len(dst) < len(src), CryptBlocks should panic. It is acceptable
            // to pass a dst bigger than src, and in that case, CryptBlocks will
            // only update dst[:len(src)] and will not touch the rest of dst.
            //
            // Multiple calls to CryptBlocks behave as if the concatenation of
            // the src buffers was passed in a single run. That is, BlockMode
            // maintains state and does not reset at each CryptBlocks call.
            CryptBlocks(dst, src []byte)
        }

        func NewCBCDecrypter

        func NewCBCDecrypter(b Block, iv []byte) BlockMode

        NewCBCDecrypter returns a BlockMode which decrypts in cipher block chaining mode, using the given Block. The length of iv must be the same as the Block's block size and must match the iv used to encrypt the data.

        Example

        Code:

        // Load your secret key from a safe place and reuse it across multiple
        // NewCipher calls. (Obviously don't use this example key for anything
        // real.) If you want to convert a passphrase to a key, use a suitable
        // package like bcrypt or scrypt.
        key, _ := hex.DecodeString("6368616e676520746869732070617373")
        ciphertext, _ := hex.DecodeString("73c86d43a9d700a253a96c85b0f6b03ac9792e0e757f869cca306bd3cba1c62b")
        
        block, err := aes.NewCipher(key)
        if err != nil {
            panic(err)
        }
        
        // The IV needs to be unique, but not secure. Therefore it's common to
        // include it at the beginning of the ciphertext.
        if len(ciphertext) < aes.BlockSize {
            panic("ciphertext too short")
        }
        iv := ciphertext[:aes.BlockSize]
        ciphertext = ciphertext[aes.BlockSize:]
        
        // CBC mode always works in whole blocks.
        if len(ciphertext)%aes.BlockSize != 0 {
            panic("ciphertext is not a multiple of the block size")
        }
        
        mode := cipher.NewCBCDecrypter(block, iv)
        
        // CryptBlocks can work in-place if the two arguments are the same.
        mode.CryptBlocks(ciphertext, ciphertext)
        
        // If the original plaintext lengths are not a multiple of the block
        // size, padding would have to be added when encrypting, which would be
        // removed at this point. For an example, see
        // https://tools.ietf.org/html/rfc5246#section-6.2.3.2. However, it's
        // critical to note that ciphertexts must be authenticated (i.e. by
        // using crypto/hmac) before being decrypted in order to avoid creating
        // a padding oracle.
        
        fmt.Printf("%s\n", ciphertext)
        

        Output:

        exampleplaintext
        

        func NewCBCEncrypter

        func NewCBCEncrypter(b Block, iv []byte) BlockMode

        NewCBCEncrypter returns a BlockMode which encrypts in cipher block chaining mode, using the given Block. The length of iv must be the same as the Block's block size.

        Example

        Code:

        // Load your secret key from a safe place and reuse it across multiple
        // NewCipher calls. (Obviously don't use this example key for anything
        // real.) If you want to convert a passphrase to a key, use a suitable
        // package like bcrypt or scrypt.
        key, _ := hex.DecodeString("6368616e676520746869732070617373")
        plaintext := []byte("exampleplaintext")
        
        // CBC mode works on blocks so plaintexts may need to be padded to the
        // next whole block. For an example of such padding, see
        // https://tools.ietf.org/html/rfc5246#section-6.2.3.2. Here we'll
        // assume that the plaintext is already of the correct length.
        if len(plaintext)%aes.BlockSize != 0 {
            panic("plaintext is not a multiple of the block size")
        }
        
        block, err := aes.NewCipher(key)
        if err != nil {
            panic(err)
        }
        
        // The IV needs to be unique, but not secure. Therefore it's common to
        // include it at the beginning of the ciphertext.
        ciphertext := make([]byte, aes.BlockSize+len(plaintext))
        iv := ciphertext[:aes.BlockSize]
        if _, err := io.ReadFull(rand.Reader, iv); err != nil {
            panic(err)
        }
        
        mode := cipher.NewCBCEncrypter(block, iv)
        mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
        
        // It's important to remember that ciphertexts must be authenticated
        // (i.e. by using crypto/hmac) as well as being encrypted in order to
        // be secure.
        
        fmt.Printf("%x\n", ciphertext)
        

        type Stream

        A Stream represents a stream cipher.

        type Stream interface {
            // XORKeyStream XORs each byte in the given slice with a byte from the
            // cipher's key stream. Dst and src must overlap entirely or not at all.
            //
            // If len(dst) < len(src), XORKeyStream should panic. It is acceptable
            // to pass a dst bigger than src, and in that case, XORKeyStream will
            // only update dst[:len(src)] and will not touch the rest of dst.
            //
            // Multiple calls to XORKeyStream behave as if the concatenation of
            // the src buffers was passed in a single run. That is, Stream
            // maintains state and does not reset at each XORKeyStream call.
            XORKeyStream(dst, src []byte)
        }

        func NewCFBDecrypter

        func NewCFBDecrypter(block Block, iv []byte) Stream

        NewCFBDecrypter returns a Stream which decrypts with cipher feedback mode, using the given Block. The iv must be the same length as the Block's block size.

        Example

        Code:

        // Load your secret key from a safe place and reuse it across multiple
        // NewCipher calls. (Obviously don't use this example key for anything
        // real.) If you want to convert a passphrase to a key, use a suitable
        // package like bcrypt or scrypt.
        key, _ := hex.DecodeString("6368616e676520746869732070617373")
        ciphertext, _ := hex.DecodeString("7dd015f06bec7f1b8f6559dad89f4131da62261786845100056b353194ad")
        
        block, err := aes.NewCipher(key)
        if err != nil {
            panic(err)
        }
        
        // The IV needs to be unique, but not secure. Therefore it's common to
        // include it at the beginning of the ciphertext.
        if len(ciphertext) < aes.BlockSize {
            panic("ciphertext too short")
        }
        iv := ciphertext[:aes.BlockSize]
        ciphertext = ciphertext[aes.BlockSize:]
        
        stream := cipher.NewCFBDecrypter(block, iv)
        
        // XORKeyStream can work in-place if the two arguments are the same.
        stream.XORKeyStream(ciphertext, ciphertext)
        fmt.Printf("%s", ciphertext)
        

        Output:

        some plaintext
        

        func NewCFBEncrypter

        func NewCFBEncrypter(block Block, iv []byte) Stream

        NewCFBEncrypter returns a Stream which encrypts with cipher feedback mode, using the given Block. The iv must be the same length as the Block's block size.

        Example

        Code:

        // Load your secret key from a safe place and reuse it across multiple
        // NewCipher calls. (Obviously don't use this example key for anything
        // real.) If you want to convert a passphrase to a key, use a suitable
        // package like bcrypt or scrypt.
        key, _ := hex.DecodeString("6368616e676520746869732070617373")
        plaintext := []byte("some plaintext")
        
        block, err := aes.NewCipher(key)
        if err != nil {
            panic(err)
        }
        
        // The IV needs to be unique, but not secure. Therefore it's common to
        // include it at the beginning of the ciphertext.
        ciphertext := make([]byte, aes.BlockSize+len(plaintext))
        iv := ciphertext[:aes.BlockSize]
        if _, err := io.ReadFull(rand.Reader, iv); err != nil {
            panic(err)
        }
        
        stream := cipher.NewCFBEncrypter(block, iv)
        stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
        
        // It's important to remember that ciphertexts must be authenticated
        // (i.e. by using crypto/hmac) as well as being encrypted in order to
        // be secure.
        fmt.Printf("%x\n", ciphertext)
        

        func NewCTR

        func NewCTR(block Block, iv []byte) Stream

        NewCTR returns a Stream which encrypts/decrypts using the given Block in counter mode. The length of iv must be the same as the Block's block size.

        Example

        Code:

        // Load your secret key from a safe place and reuse it across multiple
        // NewCipher calls. (Obviously don't use this example key for anything
        // real.) If you want to convert a passphrase to a key, use a suitable
        // package like bcrypt or scrypt.
        key, _ := hex.DecodeString("6368616e676520746869732070617373")
        plaintext := []byte("some plaintext")
        
        block, err := aes.NewCipher(key)
        if err != nil {
            panic(err)
        }
        
        // The IV needs to be unique, but not secure. Therefore it's common to
        // include it at the beginning of the ciphertext.
        ciphertext := make([]byte, aes.BlockSize+len(plaintext))
        iv := ciphertext[:aes.BlockSize]
        if _, err := io.ReadFull(rand.Reader, iv); err != nil {
            panic(err)
        }
        
        stream := cipher.NewCTR(block, iv)
        stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
        
        // It's important to remember that ciphertexts must be authenticated
        // (i.e. by using crypto/hmac) as well as being encrypted in order to
        // be secure.
        
        // CTR mode is the same for both encryption and decryption, so we can
        // also decrypt that ciphertext with NewCTR.
        
        plaintext2 := make([]byte, len(plaintext))
        stream = cipher.NewCTR(block, iv)
        stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:])
        
        fmt.Printf("%s\n", plaintext2)
        

        Output:

        some plaintext
        

        func NewOFB

        func NewOFB(b Block, iv []byte) Stream

        NewOFB returns a Stream that encrypts or decrypts using the block cipher b in output feedback mode. The initialization vector iv's length must be equal to b's block size.

        Example

        Code:

        // Load your secret key from a safe place and reuse it across multiple
        // NewCipher calls. (Obviously don't use this example key for anything
        // real.) If you want to convert a passphrase to a key, use a suitable
        // package like bcrypt or scrypt.
        key, _ := hex.DecodeString("6368616e676520746869732070617373")
        plaintext := []byte("some plaintext")
        
        block, err := aes.NewCipher(key)
        if err != nil {
            panic(err)
        }
        
        // The IV needs to be unique, but not secure. Therefore it's common to
        // include it at the beginning of the ciphertext.
        ciphertext := make([]byte, aes.BlockSize+len(plaintext))
        iv := ciphertext[:aes.BlockSize]
        if _, err := io.ReadFull(rand.Reader, iv); err != nil {
            panic(err)
        }
        
        stream := cipher.NewOFB(block, iv)
        stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
        
        // It's important to remember that ciphertexts must be authenticated
        // (i.e. by using crypto/hmac) as well as being encrypted in order to
        // be secure.
        
        // OFB mode is the same for both encryption and decryption, so we can
        // also decrypt that ciphertext with NewOFB.
        
        plaintext2 := make([]byte, len(plaintext))
        stream = cipher.NewOFB(block, iv)
        stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:])
        
        fmt.Printf("%s\n", plaintext2)
        

        Output:

        some plaintext
        

        type StreamReader

        StreamReader wraps a Stream into an io.Reader. It calls XORKeyStream to process each slice of data which passes through.

        type StreamReader struct {
            S Stream
            R io.Reader
        }
        

        Example

        Code:

        // Load your secret key from a safe place and reuse it across multiple
        // NewCipher calls. (Obviously don't use this example key for anything
        // real.) If you want to convert a passphrase to a key, use a suitable
        // package like bcrypt or scrypt.
        key, _ := hex.DecodeString("6368616e676520746869732070617373")
        
        encrypted, _ := hex.DecodeString("cf0495cc6f75dafc23948538e79904a9")
        bReader := bytes.NewReader(encrypted)
        
        block, err := aes.NewCipher(key)
        if err != nil {
            panic(err)
        }
        
        // If the key is unique for each ciphertext, then it's ok to use a zero
        // IV.
        var iv [aes.BlockSize]byte
        stream := cipher.NewOFB(block, iv[:])
        
        reader := &cipher.StreamReader{S: stream, R: bReader}
        // Copy the input to the output stream, decrypting as we go.
        if _, err := io.Copy(os.Stdout, reader); err != nil {
            panic(err)
        }
        
        // Note that this example is simplistic in that it omits any
        // authentication of the encrypted data. If you were actually to use
        // StreamReader in this manner, an attacker could flip arbitrary bits in
        // the output.
        
        

        Output:

        some secret text
        

        func (StreamReader) Read

        func (r StreamReader) Read(dst []byte) (n int, err error)

        type StreamWriter

        StreamWriter wraps a Stream into an io.Writer. It calls XORKeyStream to process each slice of data which passes through. If any StreamWriter.Write call returns short then the StreamWriter is out of sync and must be discarded. A StreamWriter has no internal buffering; StreamWriter.Close does not need to be called to flush write data.

        type StreamWriter struct {
            S   Stream
            W   io.Writer
            Err error // unused
        }
        

        Example

        Code:

        // Load your secret key from a safe place and reuse it across multiple
        // NewCipher calls. (Obviously don't use this example key for anything
        // real.) If you want to convert a passphrase to a key, use a suitable
        // package like bcrypt or scrypt.
        key, _ := hex.DecodeString("6368616e676520746869732070617373")
        
        bReader := bytes.NewReader([]byte("some secret text"))
        
        block, err := aes.NewCipher(key)
        if err != nil {
            panic(err)
        }
        
        // If the key is unique for each ciphertext, then it's ok to use a zero
        // IV.
        var iv [aes.BlockSize]byte
        stream := cipher.NewOFB(block, iv[:])
        
        var out bytes.Buffer
        
        writer := &cipher.StreamWriter{S: stream, W: &out}
        // Copy the input to the output buffer, encrypting as we go.
        if _, err := io.Copy(writer, bReader); err != nil {
            panic(err)
        }
        
        // Note that this example is simplistic in that it omits any
        // authentication of the encrypted data. If you were actually to use
        // StreamReader in this manner, an attacker could flip arbitrary bits in
        // the decrypted result.
        
        fmt.Printf("%x\n", out.Bytes())
        

        Output:

        cf0495cc6f75dafc23948538e79904a9
        

        func (StreamWriter) Close

        func (w StreamWriter) Close() error

        Close closes the underlying Writer and returns its Close return value, if the Writer is also an io.Closer. Otherwise it returns nil.

        func (StreamWriter) Write

        func (w StreamWriter) Write(src []byte) (n int, err error)
        des - Go Documentation Server
        ...

        Package des

        import "crypto/des"
        Overview
        Index
        Examples

        Overview ▾

        Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3.

        DES is cryptographically broken and should not be used for secure applications.

        Constants

        The DES block size in bytes.

        const BlockSize = 8

        func NewCipher

        func NewCipher(key []byte) (cipher.Block, error)

        NewCipher creates and returns a new cipher.Block.

        func NewTripleDESCipher

        func NewTripleDESCipher(key []byte) (cipher.Block, error)

        NewTripleDESCipher creates and returns a new cipher.Block.

        Example

        Code:

        // NewTripleDESCipher can also be used when EDE2 is required by
        // duplicating the first 8 bytes of the 16-byte key.
        ede2Key := []byte("example key 1234")
        
        var tripleDESKey []byte
        tripleDESKey = append(tripleDESKey, ede2Key[:16]...)
        tripleDESKey = append(tripleDESKey, ede2Key[:8]...)
        
        _, err := des.NewTripleDESCipher(tripleDESKey)
        if err != nil {
            panic(err)
        }
        
        // See crypto/cipher for how to use a cipher.Block for encryption and
        // decryption.
        

        type KeySizeError

        type KeySizeError int

        func (KeySizeError) Error

        func (k KeySizeError) Error() string
        dsa - Go Documentation Server
        ...

        Package dsa

        import "crypto/dsa"
        Overview
        Index

        Overview ▾

        Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.

        The DSA operations in this package are not implemented using constant-time algorithms.

        Deprecated: DSA is a legacy algorithm, and modern alternatives such as Ed25519 (implemented by package crypto/ed25519) should be used instead. Keys with 1024-bit moduli (L1024N160 parameters) are cryptographically weak, while bigger keys are not widely supported. Note that FIPS 186-5 no longer approves DSA for signature generation.

        Variables

        ErrInvalidPublicKey results when a public key is not usable by this code. FIPS is quite strict about the format of DSA keys, but other code may be less so. Thus, when using keys which may have been generated by other code, this error must be handled.

        var ErrInvalidPublicKey = errors.New("crypto/dsa: invalid public key")

        func GenerateKey

        func GenerateKey(priv *PrivateKey, rand io.Reader) error

        GenerateKey generates a public&private key pair. The Parameters of the PrivateKey must already be valid (see GenerateParameters).

        func GenerateParameters

        func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) error

        GenerateParameters puts a random, valid set of DSA parameters into params. This function can take many seconds, even on fast machines.

        func Sign

        func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)

        Sign signs an arbitrary length hash (which should be the result of hashing a larger message) using the private key, priv. It returns the signature as a pair of integers. The security of the private key depends on the entropy of rand.

        Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated to the byte-length of the subgroup. This function does not perform that truncation itself.

        Be aware that calling Sign with an attacker-controlled PrivateKey may require an arbitrary amount of CPU.

        func Verify

        func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool

        Verify verifies the signature in r, s of hash using the public key, pub. It reports whether the signature is valid.

        Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated to the byte-length of the subgroup. This function does not perform that truncation itself.

        type ParameterSizes

        ParameterSizes is an enumeration of the acceptable bit lengths of the primes in a set of DSA parameters. See FIPS 186-3, section 4.2.

        type ParameterSizes int
        const (
            L1024N160 ParameterSizes = iota
            L2048N224
            L2048N256
            L3072N256
        )

        type Parameters

        Parameters represents the domain parameters for a key. These parameters can be shared across many keys. The bit length of Q must be a multiple of 8.

        type Parameters struct {
            P, Q, G *big.Int
        }
        

        type PrivateKey

        PrivateKey represents a DSA private key.

        type PrivateKey struct {
            PublicKey
            X *big.Int
        }
        

        type PublicKey

        PublicKey represents a DSA public key.

        type PublicKey struct {
            Parameters
            Y *big.Int
        }
        
        ecdh - Go Documentation Server
        ...

        Package ecdh

        import "crypto/ecdh"
        Overview
        Index

        Overview ▾

        Package ecdh implements Elliptic Curve Diffie-Hellman over NIST curves and Curve25519.

        type Curve

        type Curve interface {
            // GenerateKey generates a random PrivateKey.
            //
            // Most applications should use [crypto/rand.Reader] as rand. Note that the
            // returned key does not depend deterministically on the bytes read from rand,
            // and may change between calls and/or between versions.
            GenerateKey(rand io.Reader) (*PrivateKey, error)
        
            // NewPrivateKey checks that key is valid and returns a PrivateKey.
            //
            // For NIST curves, this follows SEC 1, Version 2.0, Section 2.3.6, which
            // amounts to decoding the bytes as a fixed length big endian integer and
            // checking that the result is lower than the order of the curve. The zero
            // private key is also rejected, as the encoding of the corresponding public
            // key would be irregular.
            //
            // For X25519, this only checks the scalar length.
            NewPrivateKey(key []byte) (*PrivateKey, error)
        
            // NewPublicKey checks that key is valid and returns a PublicKey.
            //
            // For NIST curves, this decodes an uncompressed point according to SEC 1,
            // Version 2.0, Section 2.3.4. Compressed encodings and the point at
            // infinity are rejected.
            //
            // For X25519, this only checks the u-coordinate length. Adversarially
            // selected public keys can cause ECDH to return an error.
            NewPublicKey(key []byte) (*PublicKey, error)
            // contains filtered or unexported methods
        }

        func P256

        func P256() Curve

        P256 returns a Curve which implements NIST P-256 (FIPS 186-3, section D.2.3), also known as secp256r1 or prime256v1.

        Multiple invocations of this function will return the same value, which can be used for equality checks and switch statements.

        func P384

        func P384() Curve

        P384 returns a Curve which implements NIST P-384 (FIPS 186-3, section D.2.4), also known as secp384r1.

        Multiple invocations of this function will return the same value, which can be used for equality checks and switch statements.

        func P521

        func P521() Curve

        P521 returns a Curve which implements NIST P-521 (FIPS 186-3, section D.2.5), also known as secp521r1.

        Multiple invocations of this function will return the same value, which can be used for equality checks and switch statements.

        func X25519

        func X25519() Curve

        X25519 returns a Curve which implements the X25519 function over Curve25519 (RFC 7748, Section 5).

        Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

        type PrivateKey

        PrivateKey is an ECDH private key, usually kept secret.

        These keys can be parsed with crypto/x509.ParsePKCS8PrivateKey and encoded with crypto/x509.MarshalPKCS8PrivateKey. For NIST curves, they then need to be converted with crypto/ecdsa.PrivateKey.ECDH after parsing.

        type PrivateKey struct {
            // contains filtered or unexported fields
        }
        

        func (*PrivateKey) Bytes

        func (k *PrivateKey) Bytes() []byte

        Bytes returns a copy of the encoding of the private key.

        func (*PrivateKey) Curve

        func (k *PrivateKey) Curve() Curve

        func (*PrivateKey) ECDH

        func (k *PrivateKey) ECDH(remote *PublicKey) ([]byte, error)

        ECDH performs an ECDH exchange and returns the shared secret. The PrivateKey and PublicKey must use the same curve.

        For NIST curves, this performs ECDH as specified in SEC 1, Version 2.0, Section 3.3.1, and returns the x-coordinate encoded according to SEC 1, Version 2.0, Section 2.3.5. The result is never the point at infinity.

        For X25519, this performs ECDH as specified in RFC 7748, Section 6.1. If the result is the all-zero value, ECDH returns an error.

        func (*PrivateKey) Equal

        func (k *PrivateKey) Equal(x crypto.PrivateKey) bool

        Equal returns whether x represents the same private key as k.

        Note that there can be equivalent private keys with different encodings which would return false from this check but behave the same way as inputs to [ECDH].

        This check is performed in constant time as long as the key types and their curve match.

        func (*PrivateKey) Public

        func (k *PrivateKey) Public() crypto.PublicKey

        Public implements the implicit interface of all standard library private keys. See the docs of crypto.PrivateKey.

        func (*PrivateKey) PublicKey

        func (k *PrivateKey) PublicKey() *PublicKey

        type PublicKey

        PublicKey is an ECDH public key, usually a peer's ECDH share sent over the wire.

        These keys can be parsed with crypto/x509.ParsePKIXPublicKey and encoded with crypto/x509.MarshalPKIXPublicKey. For NIST curves, they then need to be converted with crypto/ecdsa.PublicKey.ECDH after parsing.

        type PublicKey struct {
            // contains filtered or unexported fields
        }
        

        func (*PublicKey) Bytes

        func (k *PublicKey) Bytes() []byte

        Bytes returns a copy of the encoding of the public key.

        func (*PublicKey) Curve

        func (k *PublicKey) Curve() Curve

        func (*PublicKey) Equal

        func (k *PublicKey) Equal(x crypto.PublicKey) bool

        Equal returns whether x represents the same public key as k.

        Note that there can be equivalent public keys with different encodings which would return false from this check but behave the same way as inputs to ECDH.

        This check is performed in constant time as long as the key types and their curve match.

        ecdsa - Go Documentation Server
        ...

        Package ecdsa

        import "crypto/ecdsa"
        Overview
        Index
        Examples

        Overview ▾

        Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-4 and SEC 1, Version 2.0.

        Signatures generated by this package are not deterministic, but entropy is mixed with the private key and the message, achieving the same level of security in case of randomness source failure.

        Example

        Code:

        privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
        if err != nil {
            panic(err)
        }
        
        msg := "hello, world"
        hash := sha256.Sum256([]byte(msg))
        
        sig, err := ecdsa.SignASN1(rand.Reader, privateKey, hash[:])
        if err != nil {
            panic(err)
        }
        fmt.Printf("signature: %x\n", sig)
        
        valid := ecdsa.VerifyASN1(&privateKey.PublicKey, hash[:], sig)
        fmt.Println("signature verified:", valid)
        

        func Sign

        func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)

        Sign signs a hash (which should be the result of hashing a larger message) using the private key, priv. If the hash is longer than the bit-length of the private key's curve order, the hash will be truncated to that length. It returns the signature as a pair of integers. Most applications should use SignASN1 instead of dealing directly with r, s.

        func SignASN1

        func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error)

        SignASN1 signs a hash (which should be the result of hashing a larger message) using the private key, priv. If the hash is longer than the bit-length of the private key's curve order, the hash will be truncated to that length. It returns the ASN.1 encoded signature.

        The signature is randomized. Most applications should use crypto/rand.Reader as rand. Note that the returned signature does not depend deterministically on the bytes read from rand, and may change between calls and/or between versions.

        func Verify

        func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool

        Verify verifies the signature in r, s of hash using the public key, pub. Its return value records whether the signature is valid. Most applications should use VerifyASN1 instead of dealing directly with r, s.

        func VerifyASN1

        func VerifyASN1(pub *PublicKey, hash, sig []byte) bool

        VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the public key, pub. Its return value records whether the signature is valid.

        type PrivateKey

        PrivateKey represents an ECDSA private key.

        type PrivateKey struct {
            PublicKey
            D *big.Int
        }
        

        func GenerateKey

        func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error)

        GenerateKey generates a new ECDSA private key for the specified curve.

        Most applications should use crypto/rand.Reader as rand. Note that the returned key does not depend deterministically on the bytes read from rand, and may change between calls and/or between versions.

        func (*PrivateKey) ECDH

        func (k *PrivateKey) ECDH() (*ecdh.PrivateKey, error)

        ECDH returns k as a ecdh.PrivateKey. It returns an error if the key is invalid according to the definition of ecdh.Curve.NewPrivateKey, or if the Curve is not supported by crypto/ecdh.

        func (*PrivateKey) Equal

        func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool

        Equal reports whether priv and x have the same value.

        See PublicKey.Equal for details on how Curve is compared.

        func (*PrivateKey) Public

        func (priv *PrivateKey) Public() crypto.PublicKey

        Public returns the public key corresponding to priv.

        func (*PrivateKey) Sign

        func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)

        Sign signs digest with priv, reading randomness from rand. The opts argument is not currently used but, in keeping with the crypto.Signer interface, should be the hash function used to digest the message.

        This method implements crypto.Signer, which is an interface to support keys where the private part is kept in, for example, a hardware module. Common uses can use the SignASN1 function in this package directly.

        type PublicKey

        PublicKey represents an ECDSA public key.

        type PublicKey struct {
            elliptic.Curve
            X, Y *big.Int
        }
        

        func (*PublicKey) ECDH

        func (k *PublicKey) ECDH() (*ecdh.PublicKey, error)

        ECDH returns k as a ecdh.PublicKey. It returns an error if the key is invalid according to the definition of ecdh.Curve.NewPublicKey, or if the Curve is not supported by crypto/ecdh.

        func (*PublicKey) Equal

        func (pub *PublicKey) Equal(x crypto.PublicKey) bool

        Equal reports whether pub and x have the same value.

        Two keys are only considered to have the same value if they have the same Curve value. Note that for example elliptic.P256 and elliptic.P256().Params() are different values, as the latter is a generic not constant time implementation.

        ed25519 - Go Documentation Server
        ...

        Package ed25519

        import "crypto/ed25519"
        Overview
        Index
        Examples

        Overview ▾

        Package ed25519 implements the Ed25519 signature algorithm. See https://ed25519.cr.yp.to/.

        These functions are also compatible with the “Ed25519” function defined in RFC 8032. However, unlike RFC 8032's formulation, this package's private key representation includes a public key suffix to make multiple signing operations with the same key more efficient. This package refers to the RFC 8032 private key as the “seed”.

        Example (Ed25519ctx)

        Code:

        pub, priv, err := GenerateKey(nil)
        if err != nil {
            log.Fatal(err)
        }
        
        msg := []byte("The quick brown fox jumps over the lazy dog")
        
        sig, err := priv.Sign(nil, msg, &Options{
            Context: "Example_ed25519ctx",
        })
        if err != nil {
            log.Fatal(err)
        }
        
        if err := VerifyWithOptions(pub, msg, sig, &Options{
            Context: "Example_ed25519ctx",
        }); err != nil {
            log.Fatal("invalid signature")
        }
        

        Constants

        const (
            // PublicKeySize is the size, in bytes, of public keys as used in this package.
            PublicKeySize = 32
            // PrivateKeySize is the size, in bytes, of private keys as used in this package.
            PrivateKeySize = 64
            // SignatureSize is the size, in bytes, of signatures generated and verified by this package.
            SignatureSize = 64
            // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032.
            SeedSize = 32
        )

        func GenerateKey

        func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error)

        GenerateKey generates a public/private key pair using entropy from rand. If rand is nil, crypto/rand.Reader will be used.

        The output of this function is deterministic, and equivalent to reading SeedSize bytes from rand, and passing them to NewKeyFromSeed.

        func Sign

        func Sign(privateKey PrivateKey, message []byte) []byte

        Sign signs the message with privateKey and returns a signature. It will panic if len(privateKey) is not PrivateKeySize.

        func Verify

        func Verify(publicKey PublicKey, message, sig []byte) bool

        Verify reports whether sig is a valid signature of message by publicKey. It will panic if len(publicKey) is not PublicKeySize.

        func VerifyWithOptions

        func VerifyWithOptions(publicKey PublicKey, message, sig []byte, opts *Options) error

        VerifyWithOptions reports whether sig is a valid signature of message by publicKey. A valid signature is indicated by returning a nil error. It will panic if len(publicKey) is not PublicKeySize.

        If opts.Hash is crypto.SHA512, the pre-hashed variant Ed25519ph is used and message is expected to be a SHA-512 hash, otherwise opts.Hash must be crypto.Hash(0) and the message must not be hashed, as Ed25519 performs two passes over messages to be signed.

        type Options

        Options can be used with PrivateKey.Sign or VerifyWithOptions to select Ed25519 variants.

        type Options struct {
            // Hash can be zero for regular Ed25519, or crypto.SHA512 for Ed25519ph.
            Hash crypto.Hash
        
            // Context, if not empty, selects Ed25519ctx or provides the context string
            // for Ed25519ph. It can be at most 255 bytes in length.
            Context string
        }
        

        func (*Options) HashFunc

        func (o *Options) HashFunc() crypto.Hash

        HashFunc returns o.Hash.

        type PrivateKey

        PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer.

        type PrivateKey []byte

        func NewKeyFromSeed

        func NewKeyFromSeed(seed []byte) PrivateKey

        NewKeyFromSeed calculates a private key from a seed. It will panic if len(seed) is not SeedSize. This function is provided for interoperability with RFC 8032. RFC 8032's private keys correspond to seeds in this package.

        func (PrivateKey) Equal

        func (priv PrivateKey) Equal(x crypto.PrivateKey) bool

        Equal reports whether priv and x have the same value.

        func (PrivateKey) Public

        func (priv PrivateKey) Public() crypto.PublicKey

        Public returns the PublicKey corresponding to priv.

        func (PrivateKey) Seed

        func (priv PrivateKey) Seed() []byte

        Seed returns the private key seed corresponding to priv. It is provided for interoperability with RFC 8032. RFC 8032's private keys correspond to seeds in this package.

        func (PrivateKey) Sign

        func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error)

        Sign signs the given message with priv. rand is ignored and can be nil.

        If opts.HashFunc() is crypto.SHA512, the pre-hashed variant Ed25519ph is used and message is expected to be a SHA-512 hash, otherwise opts.HashFunc() must be crypto.Hash(0) and the message must not be hashed, as Ed25519 performs two passes over messages to be signed.

        A value of type Options can be used as opts, or crypto.Hash(0) or crypto.SHA512 directly to select plain Ed25519 or Ed25519ph, respectively.

        type PublicKey

        PublicKey is the type of Ed25519 public keys.

        type PublicKey []byte

        func (PublicKey) Equal

        func (pub PublicKey) Equal(x crypto.PublicKey) bool

        Equal reports whether pub and x have the same value.

        elliptic - Go Documentation Server
        ...

        Package elliptic

        import "crypto/elliptic"
        Overview
        Index

        Overview ▾

        Package elliptic implements the standard NIST P-224, P-256, P-384, and P-521 elliptic curves over prime fields.

        Direct use of this package is deprecated, beyond the P224, P256, P384, and P521 values necessary to use crypto/ecdsa. Most other uses should migrate to the more efficient and safer crypto/ecdh, or to third-party modules for lower-level functionality.

        func GenerateKey

        func GenerateKey(curve Curve, rand io.Reader) (priv []byte, x, y *big.Int, err error)

        GenerateKey returns a public/private key pair. The private key is generated using the given reader, which must return random data.

        Deprecated: for ECDH, use the GenerateKey methods of the crypto/ecdh package; for ECDSA, use the GenerateKey function of the crypto/ecdsa package.

        func Marshal

        func Marshal(curve Curve, x, y *big.Int) []byte

        Marshal converts a point on the curve into the uncompressed form specified in SEC 1, Version 2.0, Section 2.3.3. If the point is not on the curve (or is the conventional point at infinity), the behavior is undefined.

        Deprecated: for ECDH, use the crypto/ecdh package. This function returns an encoding equivalent to that of PublicKey.Bytes in crypto/ecdh.

        func MarshalCompressed

        func MarshalCompressed(curve Curve, x, y *big.Int) []byte

        MarshalCompressed converts a point on the curve into the compressed form specified in SEC 1, Version 2.0, Section 2.3.3. If the point is not on the curve (or is the conventional point at infinity), the behavior is undefined.

        func Unmarshal

        func Unmarshal(curve Curve, data []byte) (x, y *big.Int)

        Unmarshal converts a point, serialized by Marshal, into an x, y pair. It is an error if the point is not in uncompressed form, is not on the curve, or is the point at infinity. On error, x = nil.

        Deprecated: for ECDH, use the crypto/ecdh package. This function accepts an encoding equivalent to that of the NewPublicKey methods in crypto/ecdh.

        func UnmarshalCompressed

        func UnmarshalCompressed(curve Curve, data []byte) (x, y *big.Int)

        UnmarshalCompressed converts a point, serialized by MarshalCompressed, into an x, y pair. It is an error if the point is not in compressed form, is not on the curve, or is the point at infinity. On error, x = nil.

        type Curve

        A Curve represents a short-form Weierstrass curve with a=-3.

        The behavior of Add, Double, and ScalarMult when the input is not a point on the curve is undefined.

        Note that the conventional point at infinity (0, 0) is not considered on the curve, although it can be returned by Add, Double, ScalarMult, or ScalarBaseMult (but not the Unmarshal or UnmarshalCompressed functions).

        Using Curve implementations besides those returned by P224, P256, P384, and P521 is deprecated.

        type Curve interface {
            // Params returns the parameters for the curve.
            Params() *CurveParams
        
            // IsOnCurve reports whether the given (x,y) lies on the curve.
            //
            // Deprecated: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
            // package. The NewPublicKey methods of NIST curves in crypto/ecdh accept
            // the same encoding as the Unmarshal function, and perform on-curve checks.
            IsOnCurve(x, y *big.Int) bool
        
            // Add returns the sum of (x1,y1) and (x2,y2).
            //
            // Deprecated: this is a low-level unsafe API.
            Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int)
        
            // Double returns 2*(x,y).
            //
            // Deprecated: this is a low-level unsafe API.
            Double(x1, y1 *big.Int) (x, y *big.Int)
        
            // ScalarMult returns k*(x,y) where k is an integer in big-endian form.
            //
            // Deprecated: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
            // package. Most uses of ScalarMult can be replaced by a call to the ECDH
            // methods of NIST curves in crypto/ecdh.
            ScalarMult(x1, y1 *big.Int, k []byte) (x, y *big.Int)
        
            // ScalarBaseMult returns k*G, where G is the base point of the group
            // and k is an integer in big-endian form.
            //
            // Deprecated: this is a low-level unsafe API. For ECDH, use the crypto/ecdh
            // package. Most uses of ScalarBaseMult can be replaced by a call to the
            // PrivateKey.PublicKey method in crypto/ecdh.
            ScalarBaseMult(k []byte) (x, y *big.Int)
        }

        func P224

        func P224() Curve

        P224 returns a Curve which implements NIST P-224 (FIPS 186-3, section D.2.2), also known as secp224r1. The CurveParams.Name of this Curve is "P-224".

        Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

        The cryptographic operations are implemented using constant-time algorithms.

        func P256

        func P256() Curve

        P256 returns a Curve which implements NIST P-256 (FIPS 186-3, section D.2.3), also known as secp256r1 or prime256v1. The CurveParams.Name of this Curve is "P-256".

        Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

        The cryptographic operations are implemented using constant-time algorithms.

        func P384

        func P384() Curve

        P384 returns a Curve which implements NIST P-384 (FIPS 186-3, section D.2.4), also known as secp384r1. The CurveParams.Name of this Curve is "P-384".

        Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

        The cryptographic operations are implemented using constant-time algorithms.

        func P521

        func P521() Curve

        P521 returns a Curve which implements NIST P-521 (FIPS 186-3, section D.2.5), also known as secp521r1. The CurveParams.Name of this Curve is "P-521".

        Multiple invocations of this function will return the same value, so it can be used for equality checks and switch statements.

        The cryptographic operations are implemented using constant-time algorithms.

        type CurveParams

        CurveParams contains the parameters of an elliptic curve and also provides a generic, non-constant time implementation of Curve.

        The generic Curve implementation is deprecated, and using custom curves (those not returned by P224, P256, P384, and P521) is not guaranteed to provide any security property.

        type CurveParams struct {
            P       *big.Int // the order of the underlying field
            N       *big.Int // the order of the base point
            B       *big.Int // the constant of the curve equation
            Gx, Gy  *big.Int // (x,y) of the base point
            BitSize int      // the size of the underlying field
            Name    string   // the canonical name of the curve
        }
        

        func (*CurveParams) Add

        func (curve *CurveParams) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int)

        Add implements [Curve.Add].

        Deprecated: the CurveParams methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224, P256, P384, or P521.

        func (*CurveParams) Double

        func (curve *CurveParams) Double(x1, y1 *big.Int) (*big.Int, *big.Int)

        Double implements [Curve.Double].

        Deprecated: the [CurveParams】 methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224, P256, P384, or P521.

        func (*CurveParams) IsOnCurve

        func (curve *CurveParams) IsOnCurve(x, y *big.Int) bool

        IsOnCurve implements [Curve.IsOnCurve].

        Deprecated: the CurveParams methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224, P256, P384, or P521.

        func (*CurveParams) Params

        func (curve *CurveParams) Params() *CurveParams

        func (*CurveParams) ScalarBaseMult

        func (curve *CurveParams) ScalarBaseMult(k []byte) (*big.Int, *big.Int)

        ScalarBaseMult implements [Curve.ScalarBaseMult].

        Deprecated: the CurveParams methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224, P256, P384, or P521.

        func (*CurveParams) ScalarMult

        func (curve *CurveParams) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int)

        ScalarMult implements [Curve.ScalarMult].

        Deprecated: the CurveParams methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the crypto/ecdh package. For ECDSA, use the crypto/ecdsa package with a Curve value returned directly from P224, P256, P384, or P521.

        hmac - Go Documentation Server
        ...

        Package hmac

        import "crypto/hmac"
        Overview
        Index

        Overview ▾

        Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198. An HMAC is a cryptographic hash that uses a key to sign a message. The receiver verifies the hash by recomputing it using the same key.

        Receivers should be careful to use Equal to compare MACs in order to avoid timing side-channels:

        // ValidMAC reports whether messageMAC is a valid HMAC tag for message.
        func ValidMAC(message, messageMAC, key []byte) bool {
        	mac := hmac.New(sha256.New, key)
        	mac.Write(message)
        	expectedMAC := mac.Sum(nil)
        	return hmac.Equal(messageMAC, expectedMAC)
        }
        

        func Equal

        func Equal(mac1, mac2 []byte) bool

        Equal compares two MACs for equality without leaking timing information.

        func New

        func New(h func() hash.Hash, key []byte) hash.Hash

        New returns a new HMAC hash using the given hash.Hash type and key. New functions like sha256.New from crypto/sha256 can be used as h. h must return a new Hash every time it is called. Note that unlike other hash implementations in the standard library, the returned Hash does not implement encoding.BinaryMarshaler or encoding.BinaryUnmarshaler.

        md5 - Go Documentation Server
        ...

        Package md5

        import "crypto/md5"
        Overview
        Index
        Examples

        Overview ▾

        Package md5 implements the MD5 hash algorithm as defined in RFC 1321.

        MD5 is cryptographically broken and should not be used for secure applications.

        Constants

        The blocksize of MD5 in bytes.

        const BlockSize = 64

        The size of an MD5 checksum in bytes.

        const Size = 16

        func New

        func New() hash.Hash

        New returns a new hash.Hash computing the MD5 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

        Example

        Code:

        h := md5.New()
        io.WriteString(h, "The fog is getting thicker!")
        io.WriteString(h, "And Leon's getting laaarger!")
        fmt.Printf("%x", h.Sum(nil))
        

        Output:

        e2c569be17396eca2a2e3c11578123ed
        

        Example (File)

        Code:

        f, err := os.Open("file.txt")
        if err != nil {
            log.Fatal(err)
        }
        defer f.Close()
        
        h := md5.New()
        if _, err := io.Copy(h, f); err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%x", h.Sum(nil))
        

        func Sum

        func Sum(data []byte) [Size]byte

        Sum returns the MD5 checksum of the data.

        Example

        Code:

        data := []byte("These pretzels are making me thirsty.")
        fmt.Printf("%x", md5.Sum(data))
        

        Output:

        b0804ec967f48520697662a204f5fe72
        
        rand - Go Documentation Server
        ...

        Package rand

        import "crypto/rand"
        Overview
        Index
        Examples

        Overview ▾

        Package rand implements a cryptographically secure random number generator.

        Variables

        Reader is a global, shared instance of a cryptographically secure random number generator.

        On Linux, FreeBSD, Dragonfly, NetBSD and Solaris, Reader uses getrandom(2) if available, /dev/urandom otherwise. On OpenBSD and macOS, Reader uses getentropy(2). On other Unix-like systems, Reader reads from /dev/urandom. On Windows systems, Reader uses the ProcessPrng API. On JS/Wasm, Reader uses the Web Crypto API. On WASIP1/Wasm, Reader uses random_get from wasi_snapshot_preview1.

        var Reader io.Reader

        func Int

        func Int(rand io.Reader, max *big.Int) (n *big.Int, err error)

        Int returns a uniform random value in [0, max). It panics if max <= 0.

        func Prime

        func Prime(rand io.Reader, bits int) (*big.Int, error)

        Prime returns a number of the given bit length that is prime with high probability. Prime will return error for any error returned by rand.Read or if bits < 2.

        func Read

        func Read(b []byte) (n int, err error)

        Read is a helper function that calls Reader.Read using io.ReadFull. On return, n == len(b) if and only if err == nil.

        Example

        This example reads 10 cryptographically secure pseudorandom numbers from rand.Reader and writes them to a byte slice.

        Code:

        c := 10
        b := make([]byte, c)
        _, err := rand.Read(b)
        if err != nil {
            fmt.Println("error:", err)
            return
        }
        // The slice should now contain random bytes instead of only zeroes.
        fmt.Println(bytes.Equal(b, make([]byte, c)))
        
        

        Output:

        false
        
        rc4 - Go Documentation Server
        ...

        Package rc4

        import "crypto/rc4"
        Overview
        Index

        Overview ▾

        Package rc4 implements RC4 encryption, as defined in Bruce Schneier's Applied Cryptography.

        RC4 is cryptographically broken and should not be used for secure applications.

        type Cipher

        A Cipher is an instance of RC4 using a particular key.

        type Cipher struct {
            // contains filtered or unexported fields
        }
        

        func NewCipher

        func NewCipher(key []byte) (*Cipher, error)

        NewCipher creates and returns a new Cipher. The key argument should be the RC4 key, at least 1 byte and at most 256 bytes.

        func (*Cipher) Reset

        func (c *Cipher) Reset()

        Reset zeros the key data and makes the Cipher unusable.

        Deprecated: Reset can't guarantee that the key will be entirely removed from the process's memory.

        func (*Cipher) XORKeyStream

        func (c *Cipher) XORKeyStream(dst, src []byte)

        XORKeyStream sets dst to the result of XORing src with the key stream. Dst and src must overlap entirely or not at all.

        type KeySizeError

        type KeySizeError int

        func (KeySizeError) Error

        func (k KeySizeError) Error() string
        rsa - Go Documentation Server
        ...

        Package rsa

        import "crypto/rsa"
        Overview
        Index
        Examples

        Overview ▾

        Package rsa implements RSA encryption as specified in PKCS #1 and RFC 8017.

        RSA is a single, fundamental operation that is used in this package to implement either public-key encryption or public-key signatures.

        The original specification for encryption and signatures with RSA is PKCS #1 and the terms "RSA encryption" and "RSA signatures" by default refer to PKCS #1 version 1.5. However, that specification has flaws and new designs should use version 2, usually called by just OAEP and PSS, where possible.

        Two sets of interfaces are included in this package. When a more abstract interface isn't necessary, there are functions for encrypting/decrypting with v1.5/OAEP and signing/verifying with v1.5/PSS. If one needs to abstract over the public key primitive, the PrivateKey type implements the Decrypter and Signer interfaces from the crypto package.

        Operations in this package are implemented using constant-time algorithms, except for GenerateKey, PrivateKey.Precompute, and PrivateKey.Validate. Every other operation only leaks the bit size of the involved values, which all depend on the selected key size.

        Index ▾

        Constants
        Variables
        func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error)
        func DecryptPKCS1v15(random io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error)
        func DecryptPKCS1v15SessionKey(random io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) error
        func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error)
        func EncryptPKCS1v15(random io.Reader, pub *PublicKey, msg []byte) ([]byte, error)
        func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error)
        func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, digest []byte, opts *PSSOptions) ([]byte, error)
        func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error
        func VerifyPSS(pub *PublicKey, hash crypto.Hash, digest []byte, sig []byte, opts *PSSOptions) error
        type CRTValue
        type OAEPOptions
        type PKCS1v15DecryptOptions
        type PSSOptions
            func (opts *PSSOptions) HashFunc() crypto.Hash
        type PrecomputedValues
        type PrivateKey
            func GenerateKey(random io.Reader, bits int) (*PrivateKey, error)
            func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error)
            func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error)
            func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool
            func (priv *PrivateKey) Precompute()
            func (priv *PrivateKey) Public() crypto.PublicKey
            func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)
            func (priv *PrivateKey) Validate() error
        type PublicKey
            func (pub *PublicKey) Equal(x crypto.PublicKey) bool
            func (pub *PublicKey) Size() int

        Package files

        notboring.go pkcs1v15.go pss.go rsa.go

        Constants

        const (
            // PSSSaltLengthAuto causes the salt in a PSS signature to be as large
            // as possible when signing, and to be auto-detected when verifying.
            PSSSaltLengthAuto = 0
            // PSSSaltLengthEqualsHash causes the salt length to equal the length
            // of the hash used in the signature.
            PSSSaltLengthEqualsHash = -1
        )

        Variables

        ErrDecryption represents a failure to decrypt a message. It is deliberately vague to avoid adaptive attacks.

        var ErrDecryption = errors.New("crypto/rsa: decryption error")

        ErrMessageTooLong is returned when attempting to encrypt or sign a message which is too large for the size of the key. When using SignPSS, this can also be returned if the size of the salt is too large.

        var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA key size")

        ErrVerification represents a failure to verify a signature. It is deliberately vague to avoid adaptive attacks.

        var ErrVerification = errors.New("crypto/rsa: verification error")

        func DecryptOAEP

        func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error)

        DecryptOAEP decrypts ciphertext using RSA-OAEP.

        OAEP is parameterised by a hash function that is used as a random oracle. Encryption and decryption of a given message must use the same hash function and sha256.New() is a reasonable choice.

        The random parameter is legacy and ignored, and it can be nil.

        The label parameter must match the value given when encrypting. See EncryptOAEP for details.

        Example

        Code:

        ciphertext, _ := hex.DecodeString("4d1ee10e8f286390258c51a5e80802844c3e6358ad6690b7285218a7c7ed7fc3a4c7b950fbd04d4b0239cc060dcc7065ca6f84c1756deb71ca5685cadbb82be025e16449b905c568a19c088a1abfad54bf7ecc67a7df39943ec511091a34c0f2348d04e058fcff4d55644de3cd1d580791d4524b92f3e91695582e6e340a1c50b6c6d78e80b4e42c5b4d45e479b492de42bbd39cc642ebb80226bb5200020d501b24a37bcc2ec7f34e596b4fd6b063de4858dbf5a4e3dd18e262eda0ec2d19dbd8e890d672b63d368768360b20c0b6b8592a438fa275e5fa7f60bef0dd39673fd3989cc54d2cb80c08fcd19dacbc265ee1c6014616b0e04ea0328c2a04e73460")
        label := []byte("orders")
        
        plaintext, err := rsa.DecryptOAEP(sha256.New(), nil, test2048Key, ciphertext, label)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Error from decryption: %s\n", err)
            return
        }
        
        fmt.Printf("Plaintext: %s\n", plaintext)
        
        // Remember that encryption only provides confidentiality. The
        // ciphertext should be signed before authenticity is assumed and, even
        // then, consider that messages might be reordered.
        

        func DecryptPKCS1v15

        func DecryptPKCS1v15(random io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error)

        DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS #1 v1.5. The random parameter is legacy and ignored, and it can be nil.

        Note that whether this function returns an error or not discloses secret information. If an attacker can cause this function to run repeatedly and learn whether each instance returned an error then they can decrypt and forge signatures as if they had the private key. See DecryptPKCS1v15SessionKey for a way of solving this problem.

        func DecryptPKCS1v15SessionKey

        func DecryptPKCS1v15SessionKey(random io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) error

        DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS #1 v1.5. The random parameter is legacy and ignored, and it can be nil.

        DecryptPKCS1v15SessionKey returns an error if the ciphertext is the wrong length or if the ciphertext is greater than the public modulus. Otherwise, no error is returned. If the padding is valid, the resulting plaintext message is copied into key. Otherwise, key is unchanged. These alternatives occur in constant time. It is intended that the user of this function generate a random session key beforehand and continue the protocol with the resulting value.

        Note that if the session key is too small then it may be possible for an attacker to brute-force it. If they can do that then they can learn whether a random value was used (because it'll be different for the same ciphertext) and thus whether the padding was correct. This also defeats the point of this function. Using at least a 16-byte key will protect against this attack.

        This method implements protections against Bleichenbacher chosen ciphertext attacks [0] described in RFC 3218 Section 2.3.2 [1]. While these protections make a Bleichenbacher attack significantly more difficult, the protections are only effective if the rest of the protocol which uses DecryptPKCS1v15SessionKey is designed with these considerations in mind. In particular, if any subsequent operations which use the decrypted session key leak any information about the key (e.g. whether it is a static or random key) then the mitigations are defeated. This method must be used extremely carefully, and typically should only be used when absolutely necessary for compatibility with an existing protocol (such as TLS) that is designed with these properties in mind.

        • [0] “Chosen Ciphertext Attacks Against Protocols Based on the RSA Encryption Standard PKCS #1”, Daniel Bleichenbacher, Advances in Cryptology (Crypto '98)
        • [1] RFC 3218, Preventing the Million Message Attack on CMS, https://www.rfc-editor.org/rfc/rfc3218.html

        Example

        RSA is able to encrypt only a very limited amount of data. In order to encrypt reasonable amounts of data a hybrid scheme is commonly used: RSA is used to encrypt a key for a symmetric primitive like AES-GCM. Before encrypting, data is “padded” by embedding it in a known structure. This is done for a number of reasons, but the most obvious is to ensure that the value is large enough that the exponentiation is larger than the modulus. (Otherwise it could be decrypted with a square-root.) In these designs, when using PKCS #1 v1.5, it's vitally important to avoid disclosing whether the received RSA message was well-formed (that is, whether the result of decrypting is a correctly padded message) because this leaks secret information. DecryptPKCS1v15SessionKey is designed for this situation and copies the decrypted, symmetric key (if well-formed) in constant-time over a buffer that contains a random key. Thus, if the RSA result isn't well-formed, the implementation uses a random key in constant time.

        Code:

        // The hybrid scheme should use at least a 16-byte symmetric key. Here
        // we read the random key that will be used if the RSA decryption isn't
        // well-formed.
        key := make([]byte, 32)
        if _, err := rand.Read(key); err != nil {
            panic("RNG failure")
        }
        
        rsaCiphertext, _ := hex.DecodeString("aabbccddeeff")
        
        if err := rsa.DecryptPKCS1v15SessionKey(nil, rsaPrivateKey, rsaCiphertext, key); err != nil {
            // Any errors that result will be “public” – meaning that they
            // can be determined without any secret information. (For
            // instance, if the length of key is impossible given the RSA
            // public key.)
            fmt.Fprintf(os.Stderr, "Error from RSA decryption: %s\n", err)
            return
        }
        
        // Given the resulting key, a symmetric scheme can be used to decrypt a
        // larger ciphertext.
        block, err := aes.NewCipher(key)
        if err != nil {
            panic("aes.NewCipher failed: " + err.Error())
        }
        
        // Since the key is random, using a fixed nonce is acceptable as the
        // (key, nonce) pair will still be unique, as required.
        var zeroNonce [12]byte
        aead, err := cipher.NewGCM(block)
        if err != nil {
            panic("cipher.NewGCM failed: " + err.Error())
        }
        ciphertext, _ := hex.DecodeString("00112233445566")
        plaintext, err := aead.Open(nil, zeroNonce[:], ciphertext, nil)
        if err != nil {
            // The RSA ciphertext was badly formed; the decryption will
            // fail here because the AES-GCM key will be incorrect.
            fmt.Fprintf(os.Stderr, "Error decrypting: %s\n", err)
            return
        }
        
        fmt.Printf("Plaintext: %s\n", plaintext)
        

        func EncryptOAEP

        func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error)

        EncryptOAEP encrypts the given message with RSA-OAEP.

        OAEP is parameterised by a hash function that is used as a random oracle. Encryption and decryption of a given message must use the same hash function and sha256.New() is a reasonable choice.

        The random parameter is used as a source of entropy to ensure that encrypting the same message twice doesn't result in the same ciphertext. Most applications should use crypto/rand.Reader as random.

        The label parameter may contain arbitrary data that will not be encrypted, but which gives important context to the message. For example, if a given public key is used to encrypt two types of messages then distinct label values could be used to ensure that a ciphertext for one purpose cannot be used for another by an attacker. If not required it can be empty.

        The message must be no longer than the length of the public modulus minus twice the hash length, minus a further 2.

        Example

        Code:

        secretMessage := []byte("send reinforcements, we're going to advance")
        label := []byte("orders")
        
        // crypto/rand.Reader is a good source of entropy for randomizing the
        // encryption function.
        rng := rand.Reader
        
        ciphertext, err := rsa.EncryptOAEP(sha256.New(), rng, &test2048Key.PublicKey, secretMessage, label)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Error from encryption: %s\n", err)
            return
        }
        
        // Since encryption is a randomized function, ciphertext will be
        // different each time.
        fmt.Printf("Ciphertext: %x\n", ciphertext)
        

        func EncryptPKCS1v15

        func EncryptPKCS1v15(random io.Reader, pub *PublicKey, msg []byte) ([]byte, error)

        EncryptPKCS1v15 encrypts the given message with RSA and the padding scheme from PKCS #1 v1.5. The message must be no longer than the length of the public modulus minus 11 bytes.

        The random parameter is used as a source of entropy to ensure that encrypting the same message twice doesn't result in the same ciphertext. Most applications should use crypto/rand.Reader as random. Note that the returned ciphertext does not depend deterministically on the bytes read from random, and may change between calls and/or between versions.

        WARNING: use of this function to encrypt plaintexts other than session keys is dangerous. Use RSA OAEP in new protocols.

        func SignPKCS1v15

        func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error)

        SignPKCS1v15 calculates the signature of hashed using RSASSA-PKCS1-V1_5-SIGN from RSA PKCS #1 v1.5. Note that hashed must be the result of hashing the input message using the given hash function. If hash is zero, hashed is signed directly. This isn't advisable except for interoperability.

        The random parameter is legacy and ignored, and it can be nil.

        This function is deterministic. Thus, if the set of possible messages is small, an attacker may be able to build a map from messages to signatures and identify the signed messages. As ever, signatures provide authenticity, not confidentiality.

        Example

        Code:

        message := []byte("message to be signed")
        
        // Only small messages can be signed directly; thus the hash of a
        // message, rather than the message itself, is signed. This requires
        // that the hash function be collision resistant. SHA-256 is the
        // least-strong hash function that should be used for this at the time
        // of writing (2016).
        hashed := sha256.Sum256(message)
        
        signature, err := rsa.SignPKCS1v15(nil, rsaPrivateKey, crypto.SHA256, hashed[:])
        if err != nil {
            fmt.Fprintf(os.Stderr, "Error from signing: %s\n", err)
            return
        }
        
        fmt.Printf("Signature: %x\n", signature)
        

        func SignPSS

        func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, digest []byte, opts *PSSOptions) ([]byte, error)

        SignPSS calculates the signature of digest using PSS.

        digest must be the result of hashing the input message using the given hash function. The opts argument may be nil, in which case sensible defaults are used. If opts.Hash is set, it overrides hash.

        The signature is randomized depending on the message, key, and salt size, using bytes from rand. Most applications should use crypto/rand.Reader as rand.

        func VerifyPKCS1v15

        func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error

        VerifyPKCS1v15 verifies an RSA PKCS #1 v1.5 signature. hashed is the result of hashing the input message using the given hash function and sig is the signature. A valid signature is indicated by returning a nil error. If hash is zero then hashed is used directly. This isn't advisable except for interoperability.

        Example

        Code:

        message := []byte("message to be signed")
        signature, _ := hex.DecodeString("ad2766728615cc7a746cc553916380ca7bfa4f8983b990913bc69eb0556539a350ff0f8fe65ddfd3ebe91fe1c299c2fac135bc8c61e26be44ee259f2f80c1530")
        
        // Only small messages can be signed directly; thus the hash of a
        // message, rather than the message itself, is signed. This requires
        // that the hash function be collision resistant. SHA-256 is the
        // least-strong hash function that should be used for this at the time
        // of writing (2016).
        hashed := sha256.Sum256(message)
        
        err := rsa.VerifyPKCS1v15(&rsaPrivateKey.PublicKey, crypto.SHA256, hashed[:], signature)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Error from verification: %s\n", err)
            return
        }
        
        // signature is a valid signature of message from the public key.
        

        func VerifyPSS

        func VerifyPSS(pub *PublicKey, hash crypto.Hash, digest []byte, sig []byte, opts *PSSOptions) error

        VerifyPSS verifies a PSS signature.

        A valid signature is indicated by returning a nil error. digest must be the result of hashing the input message using the given hash function. The opts argument may be nil, in which case sensible defaults are used. opts.Hash is ignored.

        type CRTValue

        CRTValue contains the precomputed Chinese remainder theorem values.

        type CRTValue struct {
            Exp   *big.Int // D mod (prime-1).
            Coeff *big.Int // R·Coeff ≡ 1 mod Prime.
            R     *big.Int // product of primes prior to this (inc p and q).
        }
        

        type OAEPOptions

        OAEPOptions is an interface for passing options to OAEP decryption using the crypto.Decrypter interface.

        type OAEPOptions struct {
            // Hash is the hash function that will be used when generating the mask.
            Hash crypto.Hash
        
            // MGFHash is the hash function used for MGF1.
            // If zero, Hash is used instead.
            MGFHash crypto.Hash
        
            // Label is an arbitrary byte string that must be equal to the value
            // used when encrypting.
            Label []byte
        }
        

        type PKCS1v15DecryptOptions

        PKCS1v15DecryptOptions is for passing options to PKCS #1 v1.5 decryption using the crypto.Decrypter interface.

        type PKCS1v15DecryptOptions struct {
            // SessionKeyLen is the length of the session key that is being
            // decrypted. If not zero, then a padding error during decryption will
            // cause a random plaintext of this length to be returned rather than
            // an error. These alternatives happen in constant time.
            SessionKeyLen int
        }
        

        type PSSOptions

        PSSOptions contains options for creating and verifying PSS signatures.

        type PSSOptions struct {
            // SaltLength controls the length of the salt used in the PSS signature. It
            // can either be a positive number of bytes, or one of the special
            // PSSSaltLength constants.
            SaltLength int
        
            // Hash is the hash function used to generate the message digest. If not
            // zero, it overrides the hash function passed to SignPSS. It's required
            // when using PrivateKey.Sign.
            Hash crypto.Hash
        }
        

        func (*PSSOptions) HashFunc

        func (opts *PSSOptions) HashFunc() crypto.Hash

        HashFunc returns opts.Hash so that PSSOptions implements crypto.SignerOpts.

        type PrecomputedValues

        type PrecomputedValues struct {
            Dp, Dq *big.Int // D mod (P-1) (or mod Q-1)
            Qinv   *big.Int // Q^-1 mod P
        
            // CRTValues is used for the 3rd and subsequent primes. Due to a
            // historical accident, the CRT for the first two primes is handled
            // differently in PKCS #1 and interoperability is sufficiently
            // important that we mirror this.
            //
            // Deprecated: These values are still filled in by Precompute for
            // backwards compatibility but are not used. Multi-prime RSA is very rare,
            // and is implemented by this package without CRT optimizations to limit
            // complexity.
            CRTValues []CRTValue
            // contains filtered or unexported fields
        }
        

        type PrivateKey

        A PrivateKey represents an RSA key

        type PrivateKey struct {
            PublicKey            // public part.
            D         *big.Int   // private exponent
            Primes    []*big.Int // prime factors of N, has >= 2 elements.
        
            // Precomputed contains precomputed values that speed up RSA operations,
            // if available. It must be generated by calling PrivateKey.Precompute and
            // must not be modified.
            Precomputed PrecomputedValues
        }
        

        func GenerateKey

        func GenerateKey(random io.Reader, bits int) (*PrivateKey, error)

        GenerateKey generates a random RSA private key of the given bit size.

        Most applications should use crypto/rand.Reader as rand. Note that the returned key does not depend deterministically on the bytes read from rand, and may change between calls and/or between versions.

        func GenerateMultiPrimeKey

        func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error)

        GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit size and the given random source.

        Table 1 in "On the Security of Multi-prime RSA" suggests maximum numbers of primes for a given bit size.

        Although the public keys are compatible (actually, indistinguishable) from the 2-prime case, the private keys are not. Thus it may not be possible to export multi-prime private keys in certain formats or to subsequently import them into other code.

        This package does not implement CRT optimizations for multi-prime RSA, so the keys with more than two primes will have worse performance.

        Deprecated: The use of this function with a number of primes different from two is not recommended for the above security, compatibility, and performance reasons. Use GenerateKey instead.

        func (*PrivateKey) Decrypt

        func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error)

        Decrypt decrypts ciphertext with priv. If opts is nil or of type *PKCS1v15DecryptOptions then PKCS #1 v1.5 decryption is performed. Otherwise opts must have type *OAEPOptions and OAEP decryption is done.

        func (*PrivateKey) Equal

        func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool

        Equal reports whether priv and x have equivalent values. It ignores Precomputed values.

        func (*PrivateKey) Precompute

        func (priv *PrivateKey) Precompute()

        Precompute performs some calculations that speed up private key operations in the future.

        func (*PrivateKey) Public

        func (priv *PrivateKey) Public() crypto.PublicKey

        Public returns the public key corresponding to priv.

        func (*PrivateKey) Sign

        func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)

        Sign signs digest with priv, reading randomness from rand. If opts is a *PSSOptions then the PSS algorithm will be used, otherwise PKCS #1 v1.5 will be used. digest must be the result of hashing the input message using opts.HashFunc().

        This method implements crypto.Signer, which is an interface to support keys where the private part is kept in, for example, a hardware module. Common uses should use the Sign* functions in this package directly.

        func (*PrivateKey) Validate

        func (priv *PrivateKey) Validate() error

        Validate performs basic sanity checks on the key. It returns nil if the key is valid, or else an error describing a problem.

        type PublicKey

        A PublicKey represents the public part of an RSA key.

        The value of the modulus N is considered secret by this library and protected from leaking through timing side-channels. However, neither the value of the exponent E nor the precise bit size of N are similarly protected.

        type PublicKey struct {
            N *big.Int // modulus
            E int      // public exponent
        }
        

        func (*PublicKey) Equal

        func (pub *PublicKey) Equal(x crypto.PublicKey) bool

        Equal reports whether pub and x have the same value.

        func (*PublicKey) Size

        func (pub *PublicKey) Size() int

        Size returns the modulus size in bytes. Raw signatures and ciphertexts for or by this public key will have the same size.

        sha1 - Go Documentation Server
        ...

        Package sha1

        import "crypto/sha1"
        Overview
        Index
        Examples

        Overview ▾

        Package sha1 implements the SHA-1 hash algorithm as defined in RFC 3174.

        SHA-1 is cryptographically broken and should not be used for secure applications.

        Constants

        The blocksize of SHA-1 in bytes.

        const BlockSize = 64

        The size of a SHA-1 checksum in bytes.

        const Size = 20

        func New

        func New() hash.Hash

        New returns a new hash.Hash computing the SHA1 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

        Example

        Code:

        h := sha1.New()
        io.WriteString(h, "His money is twice tainted:")
        io.WriteString(h, " 'taint yours and 'taint mine.")
        fmt.Printf("% x", h.Sum(nil))
        

        Output:

        59 7f 6a 54 00 10 f9 4c 15 d7 18 06 a9 9a 2c 87 10 e7 47 bd
        

        Example (File)

        Code:

        f, err := os.Open("file.txt")
        if err != nil {
            log.Fatal(err)
        }
        defer f.Close()
        
        h := sha1.New()
        if _, err := io.Copy(h, f); err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("% x", h.Sum(nil))
        

        func Sum

        func Sum(data []byte) [Size]byte

        Sum returns the SHA-1 checksum of the data.

        Example

        Code:

        data := []byte("This page intentionally left blank.")
        fmt.Printf("% x", sha1.Sum(data))
        

        Output:

        af 06 49 23 bb f2 30 15 96 aa c4 c2 73 ba 32 17 8e bc 4a 96
        
        sha256 - Go Documentation Server
        ...

        Package sha256

        import "crypto/sha256"
        Overview
        Index
        Examples

        Overview ▾

        Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.

        Constants

        The blocksize of SHA256 and SHA224 in bytes.

        const BlockSize = 64

        The size of a SHA256 checksum in bytes.

        const Size = 32

        The size of a SHA224 checksum in bytes.

        const Size224 = 28

        func New

        func New() hash.Hash

        New returns a new hash.Hash computing the SHA256 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

        Example

        Code:

        h := sha256.New()
        h.Write([]byte("hello world\n"))
        fmt.Printf("%x", h.Sum(nil))
        

        Output:

        a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447
        

        Example (File)

        Code:

        f, err := os.Open("file.txt")
        if err != nil {
            log.Fatal(err)
        }
        defer f.Close()
        
        h := sha256.New()
        if _, err := io.Copy(h, f); err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%x", h.Sum(nil))
        

        func New224

        func New224() hash.Hash

        New224 returns a new hash.Hash computing the SHA224 checksum.

        func Sum224

        func Sum224(data []byte) [Size224]byte

        Sum224 returns the SHA224 checksum of the data.

        func Sum256

        func Sum256(data []byte) [Size]byte

        Sum256 returns the SHA256 checksum of the data.

        Example

        Code:

        sum := sha256.Sum256([]byte("hello world\n"))
        fmt.Printf("%x", sum)
        

        Output:

        a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447
        
        sha512 - Go Documentation Server
        ...

        Package sha512

        import "crypto/sha512"
        Overview
        Index

        Overview ▾

        Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.

        All the hash.Hash implementations returned by this package also implement encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

        Constants

        const (
            // Size is the size, in bytes, of a SHA-512 checksum.
            Size = 64
        
            // Size224 is the size, in bytes, of a SHA-512/224 checksum.
            Size224 = 28
        
            // Size256 is the size, in bytes, of a SHA-512/256 checksum.
            Size256 = 32
        
            // Size384 is the size, in bytes, of a SHA-384 checksum.
            Size384 = 48
        
            // BlockSize is the block size, in bytes, of the SHA-512/224,
            // SHA-512/256, SHA-384 and SHA-512 hash functions.
            BlockSize = 128
        )

        func New

        func New() hash.Hash

        New returns a new hash.Hash computing the SHA-512 checksum.

        func New384

        func New384() hash.Hash

        New384 returns a new hash.Hash computing the SHA-384 checksum.

        func New512_224

        func New512_224() hash.Hash

        New512_224 returns a new hash.Hash computing the SHA-512/224 checksum.

        func New512_256

        func New512_256() hash.Hash

        New512_256 returns a new hash.Hash computing the SHA-512/256 checksum.

        func Sum384

        func Sum384(data []byte) [Size384]byte

        Sum384 returns the SHA384 checksum of the data.

        func Sum512

        func Sum512(data []byte) [Size]byte

        Sum512 returns the SHA512 checksum of the data.

        func Sum512_224

        func Sum512_224(data []byte) [Size224]byte

        Sum512_224 returns the Sum512/224 checksum of the data.

        func Sum512_256

        func Sum512_256(data []byte) [Size256]byte

        Sum512_256 returns the Sum512/256 checksum of the data.

        subtle - Go Documentation Server
        ...

        Package subtle

        import "crypto/subtle"
        Overview
        Index

        Overview ▾

        Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.

        func ConstantTimeByteEq

        func ConstantTimeByteEq(x, y uint8) int

        ConstantTimeByteEq returns 1 if x == y and 0 otherwise.

        func ConstantTimeCompare

        func ConstantTimeCompare(x, y []byte) int

        ConstantTimeCompare returns 1 if the two slices, x and y, have equal contents and 0 otherwise. The time taken is a function of the length of the slices and is independent of the contents. If the lengths of x and y do not match it returns 0 immediately.

        func ConstantTimeCopy

        func ConstantTimeCopy(v int, x, y []byte)

        ConstantTimeCopy copies the contents of y into x (a slice of equal length) if v == 1. If v == 0, x is left unchanged. Its behavior is undefined if v takes any other value.

        func ConstantTimeEq

        func ConstantTimeEq(x, y int32) int

        ConstantTimeEq returns 1 if x == y and 0 otherwise.

        func ConstantTimeLessOrEq

        func ConstantTimeLessOrEq(x, y int) int

        ConstantTimeLessOrEq returns 1 if x <= y and 0 otherwise. Its behavior is undefined if x or y are negative or > 2**31 - 1.

        func ConstantTimeSelect

        func ConstantTimeSelect(v, x, y int) int

        ConstantTimeSelect returns x if v == 1 and y if v == 0. Its behavior is undefined if v takes any other value.

        func XORBytes

        func XORBytes(dst, x, y []byte) int

        XORBytes sets dst[i] = x[i] ^ y[i] for all i < n = min(len(x), len(y)), returning n, the number of bytes written to dst. If dst does not have length at least n, XORBytes panics without writing anything to dst.

        tls - Go Documentation Server
        ...

        Package tls

        import "crypto/tls"
        Overview
        Index
        Examples
        Subdirectories

        Overview ▾

        Package tls partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.

        Index ▾

        Constants
        func CipherSuiteName(id uint16) string
        func Listen(network, laddr string, config *Config) (net.Listener, error)
        func NewListener(inner net.Listener, config *Config) net.Listener
        func VersionName(version uint16) string
        type AlertError
            func (e AlertError) Error() string
        type Certificate
            func LoadX509KeyPair(certFile, keyFile string) (Certificate, error)
            func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error)
        type CertificateRequestInfo
            func (c *CertificateRequestInfo) Context() context.Context
            func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error
        type CertificateVerificationError
            func (e *CertificateVerificationError) Error() string
            func (e *CertificateVerificationError) Unwrap() error
        type CipherSuite
            func CipherSuites() []*CipherSuite
            func InsecureCipherSuites() []*CipherSuite
        type ClientAuthType
            func (i ClientAuthType) String() string
        type ClientHelloInfo
            func (c *ClientHelloInfo) Context() context.Context
            func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error
        type ClientSessionCache
            func NewLRUClientSessionCache(capacity int) ClientSessionCache
        type ClientSessionState
            func NewResumptionState(ticket []byte, state *SessionState) (*ClientSessionState, error)
            func (cs *ClientSessionState) ResumptionState() (ticket []byte, state *SessionState, err error)
        type Config
            func (c *Config) BuildNameToCertificate()
            func (c *Config) Clone() *Config
            func (c *Config) DecryptTicket(identity []byte, cs ConnectionState) (*SessionState, error)
            func (c *Config) EncryptTicket(cs ConnectionState, ss *SessionState) ([]byte, error)
            func (c *Config) SetSessionTicketKeys(keys [][32]byte)
        type Conn
            func Client(conn net.Conn, config *Config) *Conn
            func Dial(network, addr string, config *Config) (*Conn, error)
            func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error)
            func Server(conn net.Conn, config *Config) *Conn
            func (c *Conn) Close() error
            func (c *Conn) CloseWrite() error
            func (c *Conn) ConnectionState() ConnectionState
            func (c *Conn) Handshake() error
            func (c *Conn) HandshakeContext(ctx context.Context) error
            func (c *Conn) LocalAddr() net.Addr
            func (c *Conn) NetConn() net.Conn
            func (c *Conn) OCSPResponse() []byte
            func (c *Conn) Read(b []byte) (int, error)
            func (c *Conn) RemoteAddr() net.Addr
            func (c *Conn) SetDeadline(t time.Time) error
            func (c *Conn) SetReadDeadline(t time.Time) error
            func (c *Conn) SetWriteDeadline(t time.Time) error
            func (c *Conn) VerifyHostname(host string) error
            func (c *Conn) Write(b []byte) (int, error)
        type ConnectionState
            func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error)
        type CurveID
            func (i CurveID) String() string
        type Dialer
            func (d *Dialer) Dial(network, addr string) (net.Conn, error)
            func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error)
        type QUICConfig
        type QUICConn
            func QUICClient(config *QUICConfig) *QUICConn
            func QUICServer(config *QUICConfig) *QUICConn
            func (q *QUICConn) Close() error
            func (q *QUICConn) ConnectionState() ConnectionState
            func (q *QUICConn) HandleData(level QUICEncryptionLevel, data []byte) error
            func (q *QUICConn) NextEvent() QUICEvent
            func (q *QUICConn) SendSessionTicket(opts QUICSessionTicketOptions) error
            func (q *QUICConn) SetTransportParameters(params []byte)
            func (q *QUICConn) Start(ctx context.Context) error
        type QUICEncryptionLevel
            func (l QUICEncryptionLevel) String() string
        type QUICEvent
        type QUICEventKind
        type QUICSessionTicketOptions
        type RecordHeaderError
            func (e RecordHeaderError) Error() string
        type RenegotiationSupport
        type SessionState
            func ParseSessionState(data []byte) (*SessionState, error)
            func (s *SessionState) Bytes() ([]byte, error)
        type SignatureScheme
            func (i SignatureScheme) String() string
        Bugs

        Package files

        alert.go auth.go cache.go cipher_suites.go common.go common_string.go conn.go handshake_client.go handshake_client_tls13.go handshake_messages.go handshake_server.go handshake_server_tls13.go key_agreement.go key_schedule.go notboring.go prf.go quic.go ticket.go tls.go

        Constants

        A list of cipher suite IDs that are, or have been, implemented by this package.

        See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

        const (
            // TLS 1.0 - 1.2 cipher suites.
            TLS_RSA_WITH_RC4_128_SHA                      uint16 = 0x0005
            TLS_RSA_WITH_3DES_EDE_CBC_SHA                 uint16 = 0x000a
            TLS_RSA_WITH_AES_128_CBC_SHA                  uint16 = 0x002f
            TLS_RSA_WITH_AES_256_CBC_SHA                  uint16 = 0x0035
            TLS_RSA_WITH_AES_128_CBC_SHA256               uint16 = 0x003c
            TLS_RSA_WITH_AES_128_GCM_SHA256               uint16 = 0x009c
            TLS_RSA_WITH_AES_256_GCM_SHA384               uint16 = 0x009d
            TLS_ECDHE_ECDSA_WITH_RC4_128_SHA              uint16 = 0xc007
            TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA          uint16 = 0xc009
            TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA          uint16 = 0xc00a
            TLS_ECDHE_RSA_WITH_RC4_128_SHA                uint16 = 0xc011
            TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0xc012
            TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA            uint16 = 0xc013
            TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA            uint16 = 0xc014
            TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256       uint16 = 0xc023
            TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256         uint16 = 0xc027
            TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0xc02f
            TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256       uint16 = 0xc02b
            TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384         uint16 = 0xc030
            TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384       uint16 = 0xc02c
            TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   uint16 = 0xcca8
            TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca9
        
            // TLS 1.3 cipher suites.
            TLS_AES_128_GCM_SHA256       uint16 = 0x1301
            TLS_AES_256_GCM_SHA384       uint16 = 0x1302
            TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303
        
            // TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator
            // that the client is doing version fallback. See RFC 7507.
            TLS_FALLBACK_SCSV uint16 = 0x5600
        
            // Legacy names for the corresponding cipher suites with the correct _SHA256
            // suffix, retained for backward compatibility.
            TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305   = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
            TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
        )
        const (
            VersionTLS10 = 0x0301
            VersionTLS11 = 0x0302
            VersionTLS12 = 0x0303
            VersionTLS13 = 0x0304
        
            // Deprecated: SSLv3 is cryptographically broken, and is no longer
            // supported by this package. See golang.org/issue/32716.
            VersionSSL30 = 0x0300
        )
        const (
            QUICEncryptionLevelInitial = QUICEncryptionLevel(iota)
            QUICEncryptionLevelEarly
            QUICEncryptionLevelHandshake
            QUICEncryptionLevelApplication
        )

        func CipherSuiteName

        func CipherSuiteName(id uint16) string

        CipherSuiteName returns the standard name for the passed cipher suite ID (e.g. "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"), or a fallback representation of the ID value if the cipher suite is not implemented by this package.

        func Listen

        func Listen(network, laddr string, config *Config) (net.Listener, error)

        Listen creates a TLS listener accepting connections on the given network address using net.Listen. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.

        func NewListener

        func NewListener(inner net.Listener, config *Config) net.Listener

        NewListener creates a Listener which accepts connections from an inner Listener and wraps each connection with Server. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.

        func VersionName

        func VersionName(version uint16) string

        VersionName returns the name for the provided TLS version number (e.g. "TLS 1.3"), or a fallback representation of the value if the version is not implemented by this package.

        type AlertError

        An AlertError is a TLS alert.

        When using a QUIC transport, QUICConn methods will return an error which wraps AlertError rather than sending a TLS alert.

        type AlertError uint8

        func (AlertError) Error

        func (e AlertError) Error() string

        type Certificate

        A Certificate is a chain of one or more certificates, leaf first.

        type Certificate struct {
            Certificate [][]byte
            // PrivateKey contains the private key corresponding to the public key in
            // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
            // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
            // an RSA PublicKey.
            PrivateKey crypto.PrivateKey
            // SupportedSignatureAlgorithms is an optional list restricting what
            // signature algorithms the PrivateKey can be used for.
            SupportedSignatureAlgorithms []SignatureScheme
            // OCSPStaple contains an optional OCSP response which will be served
            // to clients that request it.
            OCSPStaple []byte
            // SignedCertificateTimestamps contains an optional list of Signed
            // Certificate Timestamps which will be served to clients that request it.
            SignedCertificateTimestamps [][]byte
            // Leaf is the parsed form of the leaf certificate, which may be initialized
            // using x509.ParseCertificate to reduce per-handshake processing. If nil,
            // the leaf certificate will be parsed as needed.
            Leaf *x509.Certificate
        }
        

        func LoadX509KeyPair

        func LoadX509KeyPair(certFile, keyFile string) (Certificate, error)

        LoadX509KeyPair reads and parses a public/private key pair from a pair of files. The files must contain PEM encoded data. The certificate file may contain intermediate certificates following the leaf certificate to form a certificate chain. On successful return, Certificate.Leaf will be nil because the parsed form of the certificate is not retained.

        Example

        Code:

        cert, err := tls.LoadX509KeyPair("testdata/example-cert.pem", "testdata/example-key.pem")
        if err != nil {
            log.Fatal(err)
        }
        cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
        listener, err := tls.Listen("tcp", ":2000", cfg)
        if err != nil {
            log.Fatal(err)
        }
        _ = listener
        

        func X509KeyPair

        func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error)

        X509KeyPair parses a public/private key pair from a pair of PEM encoded data. On successful return, Certificate.Leaf will be nil because the parsed form of the certificate is not retained.

        Example

        Code:

        certPem := []byte(`-----BEGIN CERTIFICATE-----
        MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAw
        DgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlow
        EjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d
        7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B
        5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggr
        BgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1
        NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/l
        Wf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc
        6MF9+Yw1Yy0t
        -----END CERTIFICATE-----`)
        keyPem := []byte(`-----BEGIN EC PRIVATE KEY-----
        MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49
        AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8q
        EKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==
        -----END EC PRIVATE KEY-----`)
        cert, err := tls.X509KeyPair(certPem, keyPem)
        if err != nil {
            log.Fatal(err)
        }
        cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
        listener, err := tls.Listen("tcp", ":2000", cfg)
        if err != nil {
            log.Fatal(err)
        }
        _ = listener
        

        Example (HttpServer)

        Code:

        certPem := []byte(`-----BEGIN CERTIFICATE-----
        MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAw
        DgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlow
        EjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d
        7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B
        5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggr
        BgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1
        NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/l
        Wf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc
        6MF9+Yw1Yy0t
        -----END CERTIFICATE-----`)
        keyPem := []byte(`-----BEGIN EC PRIVATE KEY-----
        MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49
        AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8q
        EKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==
        -----END EC PRIVATE KEY-----`)
        cert, err := tls.X509KeyPair(certPem, keyPem)
        if err != nil {
            log.Fatal(err)
        }
        cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
        srv := &http.Server{
            TLSConfig:    cfg,
            ReadTimeout:  time.Minute,
            WriteTimeout: time.Minute,
        }
        log.Fatal(srv.ListenAndServeTLS("", ""))
        

        type CertificateRequestInfo

        CertificateRequestInfo contains information from a server's CertificateRequest message, which is used to demand a certificate and proof of control from a client.

        type CertificateRequestInfo struct {
            // AcceptableCAs contains zero or more, DER-encoded, X.501
            // Distinguished Names. These are the names of root or intermediate CAs
            // that the server wishes the returned certificate to be signed by. An
            // empty slice indicates that the server has no preference.
            AcceptableCAs [][]byte
        
            // SignatureSchemes lists the signature schemes that the server is
            // willing to verify.
            SignatureSchemes []SignatureScheme
        
            // Version is the TLS version that was negotiated for this connection.
            Version uint16
            // contains filtered or unexported fields
        }
        

        func (*CertificateRequestInfo) Context

        func (c *CertificateRequestInfo) Context() context.Context

        Context returns the context of the handshake that is in progress. This context is a child of the context passed to HandshakeContext, if any, and is canceled when the handshake concludes.

        func (*CertificateRequestInfo) SupportsCertificate

        func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error

        SupportsCertificate returns nil if the provided certificate is supported by the server that sent the CertificateRequest. Otherwise, it returns an error describing the reason for the incompatibility.

        type CertificateVerificationError

        CertificateVerificationError is returned when certificate verification fails during the handshake.

        type CertificateVerificationError struct {
            // UnverifiedCertificates and its contents should not be modified.
            UnverifiedCertificates []*x509.Certificate
            Err                    error
        }
        

        func (*CertificateVerificationError) Error

        func (e *CertificateVerificationError) Error() string

        func (*CertificateVerificationError) Unwrap

        func (e *CertificateVerificationError) Unwrap() error

        type CipherSuite

        CipherSuite is a TLS cipher suite. Note that most functions in this package accept and expose cipher suite IDs instead of this type.

        type CipherSuite struct {
            ID   uint16
            Name string
        
            // Supported versions is the list of TLS protocol versions that can
            // negotiate this cipher suite.
            SupportedVersions []uint16
        
            // Insecure is true if the cipher suite has known security issues
            // due to its primitives, design, or implementation.
            Insecure bool
        }
        

        func CipherSuites

        func CipherSuites() []*CipherSuite

        CipherSuites returns a list of cipher suites currently implemented by this package, excluding those with security issues, which are returned by InsecureCipherSuites.

        The list is sorted by ID. Note that the default cipher suites selected by this package might depend on logic that can't be captured by a static list, and might not match those returned by this function.

        func InsecureCipherSuites

        func InsecureCipherSuites() []*CipherSuite

        InsecureCipherSuites returns a list of cipher suites currently implemented by this package and which have security issues.

        Most applications should not use the cipher suites in this list, and should only use those returned by CipherSuites.

        type ClientAuthType

        ClientAuthType declares the policy the server will follow for TLS Client Authentication.

        type ClientAuthType int
        const (
            // NoClientCert indicates that no client certificate should be requested
            // during the handshake, and if any certificates are sent they will not
            // be verified.
            NoClientCert ClientAuthType = iota
            // RequestClientCert indicates that a client certificate should be requested
            // during the handshake, but does not require that the client send any
            // certificates.
            RequestClientCert
            // RequireAnyClientCert indicates that a client certificate should be requested
            // during the handshake, and that at least one certificate is required to be
            // sent by the client, but that certificate is not required to be valid.
            RequireAnyClientCert
            // VerifyClientCertIfGiven indicates that a client certificate should be requested
            // during the handshake, but does not require that the client sends a
            // certificate. If the client does send a certificate it is required to be
            // valid.
            VerifyClientCertIfGiven
            // RequireAndVerifyClientCert indicates that a client certificate should be requested
            // during the handshake, and that at least one valid certificate is required
            // to be sent by the client.
            RequireAndVerifyClientCert
        )

        func (ClientAuthType) String

        func (i ClientAuthType) String() string

        type ClientHelloInfo

        ClientHelloInfo contains information from a ClientHello message in order to guide application logic in the GetCertificate and GetConfigForClient callbacks.

        type ClientHelloInfo struct {
            // CipherSuites lists the CipherSuites supported by the client (e.g.
            // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
            CipherSuites []uint16
        
            // ServerName indicates the name of the server requested by the client
            // in order to support virtual hosting. ServerName is only set if the
            // client is using SNI (see RFC 4366, Section 3.1).
            ServerName string
        
            // SupportedCurves lists the elliptic curves supported by the client.
            // SupportedCurves is set only if the Supported Elliptic Curves
            // Extension is being used (see RFC 4492, Section 5.1.1).
            SupportedCurves []CurveID
        
            // SupportedPoints lists the point formats supported by the client.
            // SupportedPoints is set only if the Supported Point Formats Extension
            // is being used (see RFC 4492, Section 5.1.2).
            SupportedPoints []uint8
        
            // SignatureSchemes lists the signature and hash schemes that the client
            // is willing to verify. SignatureSchemes is set only if the Signature
            // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
            SignatureSchemes []SignatureScheme
        
            // SupportedProtos lists the application protocols supported by the client.
            // SupportedProtos is set only if the Application-Layer Protocol
            // Negotiation Extension is being used (see RFC 7301, Section 3.1).
            //
            // Servers can select a protocol by setting Config.NextProtos in a
            // GetConfigForClient return value.
            SupportedProtos []string
        
            // SupportedVersions lists the TLS versions supported by the client.
            // For TLS versions less than 1.3, this is extrapolated from the max
            // version advertised by the client, so values other than the greatest
            // might be rejected if used.
            SupportedVersions []uint16
        
            // Conn is the underlying net.Conn for the connection. Do not read
            // from, or write to, this connection; that will cause the TLS
            // connection to fail.
            Conn net.Conn
            // contains filtered or unexported fields
        }
        

        func (*ClientHelloInfo) Context

        func (c *ClientHelloInfo) Context() context.Context

        Context returns the context of the handshake that is in progress. This context is a child of the context passed to HandshakeContext, if any, and is canceled when the handshake concludes.

        func (*ClientHelloInfo) SupportsCertificate

        func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error

        SupportsCertificate returns nil if the provided certificate is supported by the client that sent the ClientHello. Otherwise, it returns an error describing the reason for the incompatibility.

        If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate callback, this method will take into account the associated Config. Note that if GetConfigForClient returns a different Config, the change can't be accounted for by this method.

        This function will call x509.ParseCertificate unless c.Leaf is set, which can incur a significant performance cost.

        type ClientSessionCache

        ClientSessionCache is a cache of ClientSessionState objects that can be used by a client to resume a TLS session with a given server. ClientSessionCache implementations should expect to be called concurrently from different goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which are supported via this interface.

        type ClientSessionCache interface {
            // Get searches for a ClientSessionState associated with the given key.
            // On return, ok is true if one was found.
            Get(sessionKey string) (session *ClientSessionState, ok bool)
        
            // Put adds the ClientSessionState to the cache with the given key. It might
            // get called multiple times in a connection if a TLS 1.3 server provides
            // more than one session ticket. If called with a nil *ClientSessionState,
            // it should remove the cache entry.
            Put(sessionKey string, cs *ClientSessionState)
        }

        func NewLRUClientSessionCache

        func NewLRUClientSessionCache(capacity int) ClientSessionCache

        NewLRUClientSessionCache returns a ClientSessionCache with the given capacity that uses an LRU strategy. If capacity is < 1, a default capacity is used instead.

        type ClientSessionState

        ClientSessionState contains the state needed by a client to resume a previous TLS session.

        type ClientSessionState struct {
            // contains filtered or unexported fields
        }
        

        func NewResumptionState

        func NewResumptionState(ticket []byte, state *SessionState) (*ClientSessionState, error)

        NewResumptionState returns a state value that can be returned by [ClientSessionCache.Get] to resume a previous session.

        state needs to be returned by ParseSessionState, and the ticket and session state must have been returned by ClientSessionState.ResumptionState.

        func (*ClientSessionState) ResumptionState

        func (cs *ClientSessionState) ResumptionState() (ticket []byte, state *SessionState, err error)

        ResumptionState returns the session ticket sent by the server (also known as the session's identity) and the state necessary to resume this session.

        It can be called by [ClientSessionCache.Put] to serialize (with SessionState.Bytes) and store the session.

        type Config

        A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified. A Config may be reused; the tls package will also not modify it.

        type Config struct {
            // Rand provides the source of entropy for nonces and RSA blinding.
            // If Rand is nil, TLS uses the cryptographic random reader in package
            // crypto/rand.
            // The Reader must be safe for use by multiple goroutines.
            Rand io.Reader
        
            // Time returns the current time as the number of seconds since the epoch.
            // If Time is nil, TLS uses time.Now.
            Time func() time.Time
        
            // Certificates contains one or more certificate chains to present to the
            // other side of the connection. The first certificate compatible with the
            // peer's requirements is selected automatically.
            //
            // Server configurations must set one of Certificates, GetCertificate or
            // GetConfigForClient. Clients doing client-authentication may set either
            // Certificates or GetClientCertificate.
            //
            // Note: if there are multiple Certificates, and they don't have the
            // optional field Leaf set, certificate selection will incur a significant
            // per-handshake performance cost.
            Certificates []Certificate
        
            // NameToCertificate maps from a certificate name to an element of
            // Certificates. Note that a certificate name can be of the form
            // '*.example.com' and so doesn't have to be a domain name as such.
            //
            // Deprecated: NameToCertificate only allows associating a single
            // certificate with a given name. Leave this field nil to let the library
            // select the first compatible chain from Certificates.
            NameToCertificate map[string]*Certificate
        
            // GetCertificate returns a Certificate based on the given
            // ClientHelloInfo. It will only be called if the client supplies SNI
            // information or if Certificates is empty.
            //
            // If GetCertificate is nil or returns nil, then the certificate is
            // retrieved from NameToCertificate. If NameToCertificate is nil, the
            // best element of Certificates will be used.
            //
            // Once a Certificate is returned it should not be modified.
            GetCertificate func(*ClientHelloInfo) (*Certificate, error)
        
            // GetClientCertificate, if not nil, is called when a server requests a
            // certificate from a client. If set, the contents of Certificates will
            // be ignored.
            //
            // If GetClientCertificate returns an error, the handshake will be
            // aborted and that error will be returned. Otherwise
            // GetClientCertificate must return a non-nil Certificate. If
            // Certificate.Certificate is empty then no certificate will be sent to
            // the server. If this is unacceptable to the server then it may abort
            // the handshake.
            //
            // GetClientCertificate may be called multiple times for the same
            // connection if renegotiation occurs or if TLS 1.3 is in use.
            //
            // Once a Certificate is returned it should not be modified.
            GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
        
            // GetConfigForClient, if not nil, is called after a ClientHello is
            // received from a client. It may return a non-nil Config in order to
            // change the Config that will be used to handle this connection. If
            // the returned Config is nil, the original Config will be used. The
            // Config returned by this callback may not be subsequently modified.
            //
            // If GetConfigForClient is nil, the Config passed to Server() will be
            // used for all connections.
            //
            // If SessionTicketKey was explicitly set on the returned Config, or if
            // SetSessionTicketKeys was called on the returned Config, those keys will
            // be used. Otherwise, the original Config keys will be used (and possibly
            // rotated if they are automatically managed).
            GetConfigForClient func(*ClientHelloInfo) (*Config, error)
        
            // VerifyPeerCertificate, if not nil, is called after normal
            // certificate verification by either a TLS client or server. It
            // receives the raw ASN.1 certificates provided by the peer and also
            // any verified chains that normal processing found. If it returns a
            // non-nil error, the handshake is aborted and that error results.
            //
            // If normal verification fails then the handshake will abort before
            // considering this callback. If normal verification is disabled (on the
            // client when InsecureSkipVerify is set, or on a server when ClientAuth is
            // RequestClientCert or RequireAnyClientCert), then this callback will be
            // considered but the verifiedChains argument will always be nil. When
            // ClientAuth is NoClientCert, this callback is not called on the server.
            // rawCerts may be empty on the server if ClientAuth is RequestClientCert or
            // VerifyClientCertIfGiven.
            //
            // This callback is not invoked on resumed connections, as certificates are
            // not re-verified on resumption.
            //
            // verifiedChains and its contents should not be modified.
            VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
        
            // VerifyConnection, if not nil, is called after normal certificate
            // verification and after VerifyPeerCertificate by either a TLS client
            // or server. If it returns a non-nil error, the handshake is aborted
            // and that error results.
            //
            // If normal verification fails then the handshake will abort before
            // considering this callback. This callback will run for all connections,
            // including resumptions, regardless of InsecureSkipVerify or ClientAuth
            // settings.
            VerifyConnection func(ConnectionState) error
        
            // RootCAs defines the set of root certificate authorities
            // that clients use when verifying server certificates.
            // If RootCAs is nil, TLS uses the host's root CA set.
            RootCAs *x509.CertPool
        
            // NextProtos is a list of supported application level protocols, in
            // order of preference. If both peers support ALPN, the selected
            // protocol will be one from this list, and the connection will fail
            // if there is no mutually supported protocol. If NextProtos is empty
            // or the peer doesn't support ALPN, the connection will succeed and
            // ConnectionState.NegotiatedProtocol will be empty.
            NextProtos []string
        
            // ServerName is used to verify the hostname on the returned
            // certificates unless InsecureSkipVerify is given. It is also included
            // in the client's handshake to support virtual hosting unless it is
            // an IP address.
            ServerName string
        
            // ClientAuth determines the server's policy for
            // TLS Client Authentication. The default is NoClientCert.
            ClientAuth ClientAuthType
        
            // ClientCAs defines the set of root certificate authorities
            // that servers use if required to verify a client certificate
            // by the policy in ClientAuth.
            ClientCAs *x509.CertPool
        
            // InsecureSkipVerify controls whether a client verifies the server's
            // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
            // accepts any certificate presented by the server and any host name in that
            // certificate. In this mode, TLS is susceptible to machine-in-the-middle
            // attacks unless custom verification is used. This should be used only for
            // testing or in combination with VerifyConnection or VerifyPeerCertificate.
            InsecureSkipVerify bool
        
            // CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
            // the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
            //
            // If CipherSuites is nil, a safe default list is used. The default cipher
            // suites might change over time. In Go 1.22 RSA key exchange based cipher
            // suites were removed from the default list, but can be re-added with the
            // GODEBUG setting tlsrsakex=1.
            CipherSuites []uint16
        
            // PreferServerCipherSuites is a legacy field and has no effect.
            //
            // It used to control whether the server would follow the client's or the
            // server's preference. Servers now select the best mutually supported
            // cipher suite based on logic that takes into account inferred client
            // hardware, server hardware, and security.
            //
            // Deprecated: PreferServerCipherSuites is ignored.
            PreferServerCipherSuites bool
        
            // SessionTicketsDisabled may be set to true to disable session ticket and
            // PSK (resumption) support. Note that on clients, session ticket support is
            // also disabled if ClientSessionCache is nil.
            SessionTicketsDisabled bool
        
            // SessionTicketKey is used by TLS servers to provide session resumption.
            // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
            // with random data before the first server handshake.
            //
            // Deprecated: if this field is left at zero, session ticket keys will be
            // automatically rotated every day and dropped after seven days. For
            // customizing the rotation schedule or synchronizing servers that are
            // terminating connections for the same host, use SetSessionTicketKeys.
            SessionTicketKey [32]byte
        
            // ClientSessionCache is a cache of ClientSessionState entries for TLS
            // session resumption. It is only used by clients.
            ClientSessionCache ClientSessionCache
        
            // UnwrapSession is called on the server to turn a ticket/identity
            // previously produced by [WrapSession] into a usable session.
            //
            // UnwrapSession will usually either decrypt a session state in the ticket
            // (for example with [Config.EncryptTicket]), or use the ticket as a handle
            // to recover a previously stored state. It must use [ParseSessionState] to
            // deserialize the session state.
            //
            // If UnwrapSession returns an error, the connection is terminated. If it
            // returns (nil, nil), the session is ignored. crypto/tls may still choose
            // not to resume the returned session.
            UnwrapSession func(identity []byte, cs ConnectionState) (*SessionState, error)
        
            // WrapSession is called on the server to produce a session ticket/identity.
            //
            // WrapSession must serialize the session state with [SessionState.Bytes].
            // It may then encrypt the serialized state (for example with
            // [Config.DecryptTicket]) and use it as the ticket, or store the state and
            // return a handle for it.
            //
            // If WrapSession returns an error, the connection is terminated.
            //
            // Warning: the return value will be exposed on the wire and to clients in
            // plaintext. The application is in charge of encrypting and authenticating
            // it (and rotating keys) or returning high-entropy identifiers. Failing to
            // do so correctly can compromise current, previous, and future connections
            // depending on the protocol version.
            WrapSession func(ConnectionState, *SessionState) ([]byte, error)
        
            // MinVersion contains the minimum TLS version that is acceptable.
            //
            // By default, TLS 1.2 is currently used as the minimum. TLS 1.0 is the
            // minimum supported by this package.
            //
            // The server-side default can be reverted to TLS 1.0 by including the value
            // "tls10server=1" in the GODEBUG environment variable.
            MinVersion uint16
        
            // MaxVersion contains the maximum TLS version that is acceptable.
            //
            // By default, the maximum version supported by this package is used,
            // which is currently TLS 1.3.
            MaxVersion uint16
        
            // CurvePreferences contains the elliptic curves that will be used in
            // an ECDHE handshake, in preference order. If empty, the default will
            // be used. The client will use the first preference as the type for
            // its key share in TLS 1.3. This may change in the future.
            CurvePreferences []CurveID
        
            // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
            // When true, the largest possible TLS record size is always used. When
            // false, the size of TLS records may be adjusted in an attempt to
            // improve latency.
            DynamicRecordSizingDisabled bool
        
            // Renegotiation controls what types of renegotiation are supported.
            // The default, none, is correct for the vast majority of applications.
            Renegotiation RenegotiationSupport
        
            // KeyLogWriter optionally specifies a destination for TLS master secrets
            // in NSS key log format that can be used to allow external programs
            // such as Wireshark to decrypt TLS connections.
            // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
            // Use of KeyLogWriter compromises security and should only be
            // used for debugging.
            KeyLogWriter io.Writer
            // contains filtered or unexported fields
        }
        

        Example (KeyLogWriter)

        Code:

        // Debugging TLS applications by decrypting a network traffic capture.
        
        // WARNING: Use of KeyLogWriter compromises security and should only be
        // used for debugging.
        
        // Dummy test HTTP server for the example with insecure random so output is
        // reproducible.
        server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
        server.TLS = &tls.Config{
            Rand: zeroSource{}, // for example only; don't do this.
        }
        server.StartTLS()
        defer server.Close()
        
        // Typically the log would go to an open file:
        // w, err := os.OpenFile("tls-secrets.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
        w := os.Stdout
        
        client := &http.Client{
            Transport: &http.Transport{
                TLSClientConfig: &tls.Config{
                    KeyLogWriter: w,
        
                    Rand:               zeroSource{}, // for reproducible output; don't do this.
                    InsecureSkipVerify: true,         // test server certificate is not trusted.
                },
            },
        }
        resp, err := client.Get(server.URL)
        if err != nil {
            log.Fatalf("Failed to get URL: %v", err)
        }
        resp.Body.Close()
        
        // The resulting file can be used with Wireshark to decrypt the TLS
        // connection by setting (Pre)-Master-Secret log filename in SSL Protocol
        // preferences.
        

        Example (VerifyConnection)

        Code:

        // VerifyConnection can be used to replace and customize connection
        // verification. This example shows a VerifyConnection implementation that
        // will be approximately equivalent to what crypto/tls does normally to
        // verify the peer's certificate.
        
        // Client side configuration.
        _ = &tls.Config{
            // Set InsecureSkipVerify to skip the default validation we are
            // replacing. This will not disable VerifyConnection.
            InsecureSkipVerify: true,
            VerifyConnection: func(cs tls.ConnectionState) error {
                opts := x509.VerifyOptions{
                    DNSName:       cs.ServerName,
                    Intermediates: x509.NewCertPool(),
                }
                for _, cert := range cs.PeerCertificates[1:] {
                    opts.Intermediates.AddCert(cert)
                }
                _, err := cs.PeerCertificates[0].Verify(opts)
                return err
            },
        }
        
        // Server side configuration.
        _ = &tls.Config{
            // Require client certificates (or VerifyConnection will run anyway and
            // panic accessing cs.PeerCertificates[0]) but don't verify them with the
            // default verifier. This will not disable VerifyConnection.
            ClientAuth: tls.RequireAnyClientCert,
            VerifyConnection: func(cs tls.ConnectionState) error {
                opts := x509.VerifyOptions{
                    DNSName:       cs.ServerName,
                    Intermediates: x509.NewCertPool(),
                    KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
                }
                for _, cert := range cs.PeerCertificates[1:] {
                    opts.Intermediates.AddCert(cert)
                }
                _, err := cs.PeerCertificates[0].Verify(opts)
                return err
            },
        }
        
        // Note that when certificates are not handled by the default verifier
        // ConnectionState.VerifiedChains will be nil.
        

        func (*Config) BuildNameToCertificate

        func (c *Config) BuildNameToCertificate()

        BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate from the CommonName and SubjectAlternateName fields of each of the leaf certificates.

        Deprecated: NameToCertificate only allows associating a single certificate with a given name. Leave that field nil to let the library select the first compatible chain from Certificates.

        func (*Config) Clone

        func (c *Config) Clone() *Config

        Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is being used concurrently by a TLS client or server.

        func (*Config) DecryptTicket

        func (c *Config) DecryptTicket(identity []byte, cs ConnectionState) (*SessionState, error)

        DecryptTicket decrypts a ticket encrypted by Config.EncryptTicket. It can be used as a [Config.UnwrapSession] implementation.

        If the ticket can't be decrypted or parsed, DecryptTicket returns (nil, nil).

        func (*Config) EncryptTicket

        func (c *Config) EncryptTicket(cs ConnectionState, ss *SessionState) ([]byte, error)

        EncryptTicket encrypts a ticket with the Config's configured (or default) session ticket keys. It can be used as a [Config.WrapSession] implementation.

        func (*Config) SetSessionTicketKeys

        func (c *Config) SetSessionTicketKeys(keys [][32]byte)

        SetSessionTicketKeys updates the session ticket keys for a server.

        The first key will be used when creating new tickets, while all keys can be used for decrypting tickets. It is safe to call this function while the server is running in order to rotate the session ticket keys. The function will panic if keys is empty.

        Calling this function will turn off automatic session ticket key rotation.

        If multiple servers are terminating connections for the same host they should all have the same session ticket keys. If the session ticket keys leaks, previously recorded and future TLS connections using those keys might be compromised.

        type Conn

        A Conn represents a secured connection. It implements the net.Conn interface.

        type Conn struct {
            // contains filtered or unexported fields
        }
        

        func Client

        func Client(conn net.Conn, config *Config) *Conn

        Client returns a new TLS client side connection using conn as the underlying transport. The config cannot be nil: users must set either ServerName or InsecureSkipVerify in the config.

        func Dial

        func Dial(network, addr string, config *Config) (*Conn, error)

        Dial connects to the given network address using net.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Dial interprets a nil configuration as equivalent to the zero configuration; see the documentation of Config for the defaults.

        Example

        Code:

        // Connecting with a custom root-certificate set.
        
        const rootPEM = `
        -- GlobalSign Root R2, valid until Dec 15, 2021
        -----BEGIN CERTIFICATE-----
        MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4G
        A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNp
        Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1
        MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEG
        A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI
        hvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPL
        v4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8
        eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklq
        tTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd
        C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pa
        zq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCB
        mTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IH
        V2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5n
        bG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG
        3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs
        J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO
        291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavS
        ot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd
        AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7
        TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg==
        -----END CERTIFICATE-----`
        
        // First, create the set of root certificates. For this example we only
        // have one. It's also possible to omit this in order to use the
        // default root set of the current operating system.
        roots := x509.NewCertPool()
        ok := roots.AppendCertsFromPEM([]byte(rootPEM))
        if !ok {
            panic("failed to parse root certificate")
        }
        
        conn, err := tls.Dial("tcp", "mail.google.com:443", &tls.Config{
            RootCAs: roots,
        })
        if err != nil {
            panic("failed to connect: " + err.Error())
        }
        conn.Close()
        

        func DialWithDialer

        func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error)

        DialWithDialer connects to the given network address using dialer.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Any timeout or deadline given in the dialer apply to connection and TLS handshake as a whole.

        DialWithDialer interprets a nil configuration as equivalent to the zero configuration; see the documentation of Config for the defaults.

        DialWithDialer uses context.Background internally; to specify the context, use Dialer.DialContext with NetDialer set to the desired dialer.

        func Server

        func Server(conn net.Conn, config *Config) *Conn

        Server returns a new TLS server side connection using conn as the underlying transport. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.

        func (*Conn) Close

        func (c *Conn) Close() error

        Close closes the connection.

        func (*Conn) CloseWrite

        func (c *Conn) CloseWrite() error

        CloseWrite shuts down the writing side of the connection. It should only be called once the handshake has completed and does not call CloseWrite on the underlying connection. Most callers should just use Conn.Close.

        func (*Conn) ConnectionState

        func (c *Conn) ConnectionState() ConnectionState

        ConnectionState returns basic TLS details about the connection.

        func (*Conn) Handshake

        func (c *Conn) Handshake() error

        Handshake runs the client or server handshake protocol if it has not yet been run.

        Most uses of this package need not call Handshake explicitly: the first Conn.Read or Conn.Write will call it automatically.

        For control over canceling or setting a timeout on a handshake, use Conn.HandshakeContext or the Dialer's DialContext method instead.

        In order to avoid denial of service attacks, the maximum RSA key size allowed in certificates sent by either the TLS server or client is limited to 8192 bits. This limit can be overridden by setting tlsmaxrsasize in the GODEBUG environment variable (e.g. GODEBUG=tlsmaxrsasize=4096).

        func (*Conn) HandshakeContext

        func (c *Conn) HandshakeContext(ctx context.Context) error

        HandshakeContext runs the client or server handshake protocol if it has not yet been run.

        The provided Context must be non-nil. If the context is canceled before the handshake is complete, the handshake is interrupted and an error is returned. Once the handshake has completed, cancellation of the context will not affect the connection.

        Most uses of this package need not call HandshakeContext explicitly: the first Conn.Read or Conn.Write will call it automatically.

        func (*Conn) LocalAddr

        func (c *Conn) LocalAddr() net.Addr

        LocalAddr returns the local network address.

        func (*Conn) NetConn

        func (c *Conn) NetConn() net.Conn

        NetConn returns the underlying connection that is wrapped by c. Note that writing to or reading from this connection directly will corrupt the TLS session.

        func (*Conn) OCSPResponse

        func (c *Conn) OCSPResponse() []byte

        OCSPResponse returns the stapled OCSP response from the TLS server, if any. (Only valid for client connections.)

        func (*Conn) Read

        func (c *Conn) Read(b []byte) (int, error)

        Read reads data from the connection.

        As Read calls Conn.Handshake, in order to prevent indefinite blocking a deadline must be set for both Read and Conn.Write before Read is called when the handshake has not yet completed. See Conn.SetDeadline, Conn.SetReadDeadline, and Conn.SetWriteDeadline.

        func (*Conn) RemoteAddr

        func (c *Conn) RemoteAddr() net.Addr

        RemoteAddr returns the remote network address.

        func (*Conn) SetDeadline

        func (c *Conn) SetDeadline(t time.Time) error

        SetDeadline sets the read and write deadlines associated with the connection. A zero value for t means Conn.Read and Conn.Write will not time out. After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.

        func (*Conn) SetReadDeadline

        func (c *Conn) SetReadDeadline(t time.Time) error

        SetReadDeadline sets the read deadline on the underlying connection. A zero value for t means Conn.Read will not time out.

        func (*Conn) SetWriteDeadline

        func (c *Conn) SetWriteDeadline(t time.Time) error

        SetWriteDeadline sets the write deadline on the underlying connection. A zero value for t means Conn.Write will not time out. After a Conn.Write has timed out, the TLS state is corrupt and all future writes will return the same error.

        func (*Conn) VerifyHostname

        func (c *Conn) VerifyHostname(host string) error

        VerifyHostname checks that the peer certificate chain is valid for connecting to host. If so, it returns nil; if not, it returns an error describing the problem.

        func (*Conn) Write

        func (c *Conn) Write(b []byte) (int, error)

        Write writes data to the connection.

        As Write calls Conn.Handshake, in order to prevent indefinite blocking a deadline must be set for both Conn.Read and Write before Write is called when the handshake has not yet completed. See Conn.SetDeadline, Conn.SetReadDeadline, and Conn.SetWriteDeadline.

        type ConnectionState

        ConnectionState records basic TLS details about the connection.

        type ConnectionState struct {
            // Version is the TLS version used by the connection (e.g. VersionTLS12).
            Version uint16
        
            // HandshakeComplete is true if the handshake has concluded.
            HandshakeComplete bool
        
            // DidResume is true if this connection was successfully resumed from a
            // previous session with a session ticket or similar mechanism.
            DidResume bool
        
            // CipherSuite is the cipher suite negotiated for the connection (e.g.
            // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
            CipherSuite uint16
        
            // NegotiatedProtocol is the application protocol negotiated with ALPN.
            NegotiatedProtocol string
        
            // NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
            //
            // Deprecated: this value is always true.
            NegotiatedProtocolIsMutual bool
        
            // ServerName is the value of the Server Name Indication extension sent by
            // the client. It's available both on the server and on the client side.
            ServerName string
        
            // PeerCertificates are the parsed certificates sent by the peer, in the
            // order in which they were sent. The first element is the leaf certificate
            // that the connection is verified against.
            //
            // On the client side, it can't be empty. On the server side, it can be
            // empty if Config.ClientAuth is not RequireAnyClientCert or
            // RequireAndVerifyClientCert.
            //
            // PeerCertificates and its contents should not be modified.
            PeerCertificates []*x509.Certificate
        
            // VerifiedChains is a list of one or more chains where the first element is
            // PeerCertificates[0] and the last element is from Config.RootCAs (on the
            // client side) or Config.ClientCAs (on the server side).
            //
            // On the client side, it's set if Config.InsecureSkipVerify is false. On
            // the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
            // (and the peer provided a certificate) or RequireAndVerifyClientCert.
            //
            // VerifiedChains and its contents should not be modified.
            VerifiedChains [][]*x509.Certificate
        
            // SignedCertificateTimestamps is a list of SCTs provided by the peer
            // through the TLS handshake for the leaf certificate, if any.
            SignedCertificateTimestamps [][]byte
        
            // OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
            // response provided by the peer for the leaf certificate, if any.
            OCSPResponse []byte
        
            // TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
            // Section 3). This value will be nil for TLS 1.3 connections and for
            // resumed connections that don't support Extended Master Secret (RFC 7627).
            TLSUnique []byte
            // contains filtered or unexported fields
        }
        

        func (*ConnectionState) ExportKeyingMaterial

        func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error)

        ExportKeyingMaterial returns length bytes of exported key material in a new slice as defined in RFC 5705. If context is nil, it is not used as part of the seed. If the connection was set to allow renegotiation via Config.Renegotiation, or if the connections supports neither TLS 1.3 nor Extended Master Secret, this function will return an error.

        Exporting key material without Extended Master Secret or TLS 1.3 was disabled in Go 1.22 due to security issues (see the Security Considerations sections of RFC 5705 and RFC 7627), but can be re-enabled with the GODEBUG setting tlsunsafeekm=1.

        type CurveID

        CurveID is the type of a TLS identifier for an elliptic curve. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.

        In TLS 1.3, this type is called NamedGroup, but at this time this library only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.

        type CurveID uint16
        const (
            CurveP256 CurveID = 23
            CurveP384 CurveID = 24
            CurveP521 CurveID = 25
            X25519    CurveID = 29
        )

        func (CurveID) String

        func (i CurveID) String() string

        type Dialer

        Dialer dials TLS connections given a configuration and a Dialer for the underlying connection.

        type Dialer struct {
            // NetDialer is the optional dialer to use for the TLS connections'
            // underlying TCP connections.
            // A nil NetDialer is equivalent to the net.Dialer zero value.
            NetDialer *net.Dialer
        
            // Config is the TLS configuration to use for new connections.
            // A nil configuration is equivalent to the zero
            // configuration; see the documentation of Config for the
            // defaults.
            Config *Config
        }
        

        func (*Dialer) Dial

        func (d *Dialer) Dial(network, addr string) (net.Conn, error)

        Dial connects to the given network address and initiates a TLS handshake, returning the resulting TLS connection.

        The returned Conn, if any, will always be of type *Conn.

        Dial uses context.Background internally; to specify the context, use Dialer.DialContext.

        func (*Dialer) DialContext

        func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error)

        DialContext connects to the given network address and initiates a TLS handshake, returning the resulting TLS connection.

        The provided Context must be non-nil. If the context expires before the connection is complete, an error is returned. Once successfully connected, any expiration of the context will not affect the connection.

        The returned Conn, if any, will always be of type *Conn.

        type QUICConfig

        A QUICConfig configures a QUICConn.

        type QUICConfig struct {
            TLSConfig *Config
        }
        

        type QUICConn

        A QUICConn represents a connection which uses a QUIC implementation as the underlying transport as described in RFC 9001.

        Methods of QUICConn are not safe for concurrent use.

        type QUICConn struct {
            // contains filtered or unexported fields
        }
        

        func QUICClient

        func QUICClient(config *QUICConfig) *QUICConn

        QUICClient returns a new TLS client side connection using QUICTransport as the underlying transport. The config cannot be nil.

        The config's MinVersion must be at least TLS 1.3.

        func QUICServer

        func QUICServer(config *QUICConfig) *QUICConn

        QUICServer returns a new TLS server side connection using QUICTransport as the underlying transport. The config cannot be nil.

        The config's MinVersion must be at least TLS 1.3.

        func (*QUICConn) Close

        func (q *QUICConn) Close() error

        Close closes the connection and stops any in-progress handshake.

        func (*QUICConn) ConnectionState

        func (q *QUICConn) ConnectionState() ConnectionState

        ConnectionState returns basic TLS details about the connection.

        func (*QUICConn) HandleData

        func (q *QUICConn) HandleData(level QUICEncryptionLevel, data []byte) error

        HandleData handles handshake bytes received from the peer. It may produce connection events, which may be read with QUICConn.NextEvent.

        func (*QUICConn) NextEvent

        func (q *QUICConn) NextEvent() QUICEvent

        NextEvent returns the next event occurring on the connection. It returns an event with a Kind of QUICNoEvent when no events are available.

        func (*QUICConn) SendSessionTicket

        func (q *QUICConn) SendSessionTicket(opts QUICSessionTicketOptions) error

        SendSessionTicket sends a session ticket to the client. It produces connection events, which may be read with QUICConn.NextEvent. Currently, it can only be called once.

        func (*QUICConn) SetTransportParameters

        func (q *QUICConn) SetTransportParameters(params []byte)

        SetTransportParameters sets the transport parameters to send to the peer.

        Server connections may delay setting the transport parameters until after receiving the client's transport parameters. See QUICTransportParametersRequired.

        func (*QUICConn) Start

        func (q *QUICConn) Start(ctx context.Context) error

        Start starts the client or server handshake protocol. It may produce connection events, which may be read with QUICConn.NextEvent.

        Start must be called at most once.

        type QUICEncryptionLevel

        QUICEncryptionLevel represents a QUIC encryption level used to transmit handshake messages.

        type QUICEncryptionLevel int

        func (QUICEncryptionLevel) String

        func (l QUICEncryptionLevel) String() string

        type QUICEvent

        A QUICEvent is an event occurring on a QUIC connection.

        The type of event is specified by the Kind field. The contents of the other fields are kind-specific.

        type QUICEvent struct {
            Kind QUICEventKind
        
            // Set for QUICSetReadSecret, QUICSetWriteSecret, and QUICWriteData.
            Level QUICEncryptionLevel
        
            // Set for QUICTransportParameters, QUICSetReadSecret, QUICSetWriteSecret, and QUICWriteData.
            // The contents are owned by crypto/tls, and are valid until the next NextEvent call.
            Data []byte
        
            // Set for QUICSetReadSecret and QUICSetWriteSecret.
            Suite uint16
        }
        

        type QUICEventKind

        A QUICEventKind is a type of operation on a QUIC connection.

        type QUICEventKind int
        const (
            // QUICNoEvent indicates that there are no events available.
            QUICNoEvent QUICEventKind = iota
        
            // QUICSetReadSecret and QUICSetWriteSecret provide the read and write
            // secrets for a given encryption level.
            // QUICEvent.Level, QUICEvent.Data, and QUICEvent.Suite are set.
            //
            // Secrets for the Initial encryption level are derived from the initial
            // destination connection ID, and are not provided by the QUICConn.
            QUICSetReadSecret
            QUICSetWriteSecret
        
            // QUICWriteData provides data to send to the peer in CRYPTO frames.
            // QUICEvent.Data is set.
            QUICWriteData
        
            // QUICTransportParameters provides the peer's QUIC transport parameters.
            // QUICEvent.Data is set.
            QUICTransportParameters
        
            // QUICTransportParametersRequired indicates that the caller must provide
            // QUIC transport parameters to send to the peer. The caller should set
            // the transport parameters with QUICConn.SetTransportParameters and call
            // QUICConn.NextEvent again.
            //
            // If transport parameters are set before calling QUICConn.Start, the
            // connection will never generate a QUICTransportParametersRequired event.
            QUICTransportParametersRequired
        
            // QUICRejectedEarlyData indicates that the server rejected 0-RTT data even
            // if we offered it. It's returned before QUICEncryptionLevelApplication
            // keys are returned.
            QUICRejectedEarlyData
        
            // QUICHandshakeDone indicates that the TLS handshake has completed.
            QUICHandshakeDone
        )

        type QUICSessionTicketOptions

        type QUICSessionTicketOptions struct {
            // EarlyData specifies whether the ticket may be used for 0-RTT.
            EarlyData bool
        }
        

        type RecordHeaderError

        RecordHeaderError is returned when a TLS record header is invalid.

        type RecordHeaderError struct {
            // Msg contains a human readable string that describes the error.
            Msg string
            // RecordHeader contains the five bytes of TLS record header that
            // triggered the error.
            RecordHeader [5]byte
            // Conn provides the underlying net.Conn in the case that a client
            // sent an initial handshake that didn't look like TLS.
            // It is nil if there's already been a handshake or a TLS alert has
            // been written to the connection.
            Conn net.Conn
        }
        

        func (RecordHeaderError) Error

        func (e RecordHeaderError) Error() string

        type RenegotiationSupport

        RenegotiationSupport enumerates the different levels of support for TLS renegotiation. TLS renegotiation is the act of performing subsequent handshakes on a connection after the first. This significantly complicates the state machine and has been the source of numerous, subtle security issues. Initiating a renegotiation is not supported, but support for accepting renegotiation requests may be enabled.

        Even when enabled, the server may not change its identity between handshakes (i.e. the leaf certificate must be the same). Additionally, concurrent handshake and application data flow is not permitted so renegotiation can only be used with protocols that synchronise with the renegotiation, such as HTTPS.

        Renegotiation is not defined in TLS 1.3.

        type RenegotiationSupport int
        const (
            // RenegotiateNever disables renegotiation.
            RenegotiateNever RenegotiationSupport = iota
        
            // RenegotiateOnceAsClient allows a remote server to request
            // renegotiation once per connection.
            RenegotiateOnceAsClient
        
            // RenegotiateFreelyAsClient allows a remote server to repeatedly
            // request renegotiation.
            RenegotiateFreelyAsClient
        )

        type SessionState

        A SessionState is a resumable session.

        type SessionState struct {
        
            // Extra is ignored by crypto/tls, but is encoded by [SessionState.Bytes]
            // and parsed by [ParseSessionState].
            //
            // This allows [Config.UnwrapSession]/[Config.WrapSession] and
            // [ClientSessionCache] implementations to store and retrieve additional
            // data alongside this session.
            //
            // To allow different layers in a protocol stack to share this field,
            // applications must only append to it, not replace it, and must use entries
            // that can be recognized even if out of order (for example, by starting
            // with an id and version prefix).
            Extra [][]byte
        
            // EarlyData indicates whether the ticket can be used for 0-RTT in a QUIC
            // connection. The application may set this to false if it is true to
            // decline to offer 0-RTT even if supported.
            EarlyData bool
            // contains filtered or unexported fields
        }
        

        func ParseSessionState

        func ParseSessionState(data []byte) (*SessionState, error)

        ParseSessionState parses a SessionState encoded by SessionState.Bytes.

        func (*SessionState) Bytes

        func (s *SessionState) Bytes() ([]byte, error)

        Bytes encodes the session, including any private fields, so that it can be parsed by ParseSessionState. The encoding contains secret values critical to the security of future and possibly past sessions.

        The specific encoding should be considered opaque and may change incompatibly between Go versions.

        type SignatureScheme

        SignatureScheme identifies a signature algorithm supported by TLS. See RFC 8446, Section 4.2.3.

        type SignatureScheme uint16
        const (
            // RSASSA-PKCS1-v1_5 algorithms.
            PKCS1WithSHA256 SignatureScheme = 0x0401
            PKCS1WithSHA384 SignatureScheme = 0x0501
            PKCS1WithSHA512 SignatureScheme = 0x0601
        
            // RSASSA-PSS algorithms with public key OID rsaEncryption.
            PSSWithSHA256 SignatureScheme = 0x0804
            PSSWithSHA384 SignatureScheme = 0x0805
            PSSWithSHA512 SignatureScheme = 0x0806
        
            // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
            ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
            ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
            ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
        
            // EdDSA algorithms.
            Ed25519 SignatureScheme = 0x0807
        
            // Legacy signature and hash algorithms for TLS 1.2.
            PKCS1WithSHA1 SignatureScheme = 0x0201
            ECDSAWithSHA1 SignatureScheme = 0x0203
        )

        func (SignatureScheme) String

        func (i SignatureScheme) String() string

        Bugs

        Subdirectories

        Name Synopsis
        ..
        fipsonly Package fipsonly restricts all TLS configuration to FIPS-approved settings.
        fipsonly - Go Documentation Server
        ...

        Command fipsonly

        Package fipsonly restricts all TLS configuration to FIPS-approved settings.

        The effect is triggered by importing the package anywhere in a program, as in:

        import _ "crypto/tls/fipsonly"
        

        This package only exists when using Go compiled with GOEXPERIMENT=boringcrypto.

        x509 - Go Documentation Server
        ...

        Package x509

        import "crypto/x509"
        Overview
        Index
        Examples
        Subdirectories

        Overview ▾

        Package x509 implements a subset of the X.509 standard.

        It allows parsing and generating certificates, certificate signing requests, certificate revocation lists, and encoded public and private keys. It provides a certificate verifier, complete with a chain builder.

        The package targets the X.509 technical profile defined by the IETF (RFC 2459/3280/5280), and as further restricted by the CA/Browser Forum Baseline Requirements. There is minimal support for features outside of these profiles, as the primary goal of the package is to provide compatibility with the publicly trusted TLS certificate ecosystem and its policies and constraints.

        On macOS and Windows, certificate verification is handled by system APIs, but the package aims to apply consistent validation rules across operating systems.

        Index ▾

        Variables
        func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error)
        func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error)
        func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error)
        func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)
        func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)
        func IsEncryptedPEMBlock(b *pem.Block) bool
        func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error)
        func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte
        func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte
        func MarshalPKCS8PrivateKey(key any) ([]byte, error)
        func MarshalPKIXPublicKey(pub any) ([]byte, error)
        func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error)
        func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error)
        func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)
        func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)
        func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error)
        func ParsePKCS8PrivateKey(der []byte) (key any, err error)
        func ParsePKIXPublicKey(derBytes []byte) (pub any, err error)
        func SetFallbackRoots(roots *CertPool)
        type CertPool
            func NewCertPool() *CertPool
            func SystemCertPool() (*CertPool, error)
            func (s *CertPool) AddCert(cert *Certificate)
            func (s *CertPool) AddCertWithConstraint(cert *Certificate, constraint func([]*Certificate) error)
            func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)
            func (s *CertPool) Clone() *CertPool
            func (s *CertPool) Equal(other *CertPool) bool
            func (s *CertPool) Subjects() [][]byte
        type Certificate
            func ParseCertificate(der []byte) (*Certificate, error)
            func ParseCertificates(der []byte) ([]*Certificate, error)
            func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error
            func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error
            func (c *Certificate) CheckSignatureFrom(parent *Certificate) error
            func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error)
            func (c *Certificate) Equal(other *Certificate) bool
            func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)
            func (c *Certificate) VerifyHostname(h string) error
        type CertificateInvalidError
            func (e CertificateInvalidError) Error() string
        type CertificateRequest
            func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)
            func (c *CertificateRequest) CheckSignature() error
        type ConstraintViolationError
            func (ConstraintViolationError) Error() string
        type ExtKeyUsage
        type HostnameError
            func (h HostnameError) Error() string
        type InsecureAlgorithmError
            func (e InsecureAlgorithmError) Error() string
        type InvalidReason
        type KeyUsage
        type OID
            func OIDFromInts(oid []uint64) (OID, error)
            func (oid OID) Equal(other OID) bool
            func (oid OID) EqualASN1OID(other asn1.ObjectIdentifier) bool
            func (oid OID) String() string
        type PEMCipher
        type PublicKeyAlgorithm
            func (algo PublicKeyAlgorithm) String() string
        type RevocationList
            func ParseRevocationList(der []byte) (*RevocationList, error)
            func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error
        type RevocationListEntry
        type SignatureAlgorithm
            func (algo SignatureAlgorithm) String() string
        type SystemRootsError
            func (se SystemRootsError) Error() string
            func (se SystemRootsError) Unwrap() error
        type UnhandledCriticalExtension
            func (h UnhandledCriticalExtension) Error() string
        type UnknownAuthorityError
            func (e UnknownAuthorityError) Error() string
        type VerifyOptions

        Examples

        Certificate.Verify
        ParsePKIXPublicKey

        Package files

        cert_pool.go notboring.go oid.go parser.go pem_decrypt.go pkcs1.go pkcs8.go root.go root_linux.go root_unix.go sec1.go verify.go x509.go

        Variables

        ErrUnsupportedAlgorithm results from attempting to perform an operation that involves algorithms that are not currently implemented.

        var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")

        IncorrectPasswordError is returned when an incorrect password is detected.

        var IncorrectPasswordError = errors.New("x509: decryption password incorrect")

        func CreateCertificate

        func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error)

        CreateCertificate creates a new X.509 v3 certificate based on a template. The following members of template are currently used:

        • AuthorityKeyId
        • BasicConstraintsValid
        • CRLDistributionPoints
        • DNSNames
        • EmailAddresses
        • ExcludedDNSDomains
        • ExcludedEmailAddresses
        • ExcludedIPRanges
        • ExcludedURIDomains
        • ExtKeyUsage
        • ExtraExtensions
        • IPAddresses
        • IsCA
        • IssuingCertificateURL
        • KeyUsage
        • MaxPathLen
        • MaxPathLenZero
        • NotAfter
        • NotBefore
        • OCSPServer
        • PermittedDNSDomains
        • PermittedDNSDomainsCritical
        • PermittedEmailAddresses
        • PermittedIPRanges
        • PermittedURIDomains
        • PolicyIdentifiers (see note below)
        • Policies (see note below)
        • SerialNumber
        • SignatureAlgorithm
        • Subject
        • SubjectKeyId
        • URIs
        • UnknownExtKeyUsage

        The certificate is signed by parent. If parent is equal to template then the certificate is self-signed. The parameter pub is the public key of the certificate to be generated and priv is the private key of the signer.

        The returned slice is the certificate in DER encoding.

        The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and ed25519.PublicKey. pub must be a supported key type, and priv must be a crypto.Signer with a supported public key.

        The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any, unless the resulting certificate is self-signed. Otherwise the value from template will be used.

        If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId will be generated from the hash of the public key.

        The PolicyIdentifier and Policies fields are both used to marshal certificate policy OIDs. By default, only the PolicyIdentifier is marshaled, but if the GODEBUG setting "x509usepolicies" has the value "1", the Policies field will be marshalled instead of the PolicyIdentifier field. The Policies field can be used to marshal policy OIDs which have components that are larger than 31 bits.

        func CreateCertificateRequest

        func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error)

        CreateCertificateRequest creates a new certificate request based on a template. The following members of template are used:

        • SignatureAlgorithm
        • Subject
        • DNSNames
        • EmailAddresses
        • IPAddresses
        • URIs
        • ExtraExtensions
        • Attributes (deprecated)

        priv is the private key to sign the CSR with, and the corresponding public key will be included in the CSR. It must implement crypto.Signer and its Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or ed25519.PrivateKey satisfies this.)

        The returned slice is the certificate request in DER encoding.

        func CreateRevocationList

        func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error)

        CreateRevocationList creates a new X.509 v2 Certificate Revocation List, according to RFC 5280, based on template.

        The CRL is signed by priv which should be the private key associated with the public key in the issuer certificate.

        The issuer may not be nil, and the crlSign bit must be set in KeyUsage in order to use it as a CRL issuer.

        The issuer distinguished name CRL field and authority key identifier extension are populated using the issuer certificate. issuer must have SubjectKeyId set.

        func DecryptPEMBlock

        func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)

        DecryptPEMBlock takes a PEM block encrypted according to RFC 1423 and the password used to encrypt it and returns a slice of decrypted DER encoded bytes. It inspects the DEK-Info header to determine the algorithm used for decryption. If no DEK-Info header is present, an error is returned. If an incorrect password is detected an IncorrectPasswordError is returned. Because of deficiencies in the format, it's not always possible to detect an incorrect password. In these cases no error will be returned but the decrypted DER bytes will be random noise.

        Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.

        func EncryptPEMBlock

        func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)

        EncryptPEMBlock returns a PEM block of the specified type holding the given DER encoded data encrypted with the specified algorithm and password according to RFC 1423.

        Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.

        func IsEncryptedPEMBlock

        func IsEncryptedPEMBlock(b *pem.Block) bool

        IsEncryptedPEMBlock returns whether the PEM block is password encrypted according to RFC 1423.

        Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.

        func MarshalECPrivateKey

        func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error)

        MarshalECPrivateKey converts an EC private key to SEC 1, ASN.1 DER form.

        This kind of key is commonly encoded in PEM blocks of type "EC PRIVATE KEY". For a more flexible key format which is not EC specific, use MarshalPKCS8PrivateKey.

        func MarshalPKCS1PrivateKey

        func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte

        MarshalPKCS1PrivateKey converts an RSA private key to PKCS #1, ASN.1 DER form.

        This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY". For a more flexible key format which is not RSA specific, use MarshalPKCS8PrivateKey.

        func MarshalPKCS1PublicKey

        func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte

        MarshalPKCS1PublicKey converts an RSA public key to PKCS #1, ASN.1 DER form.

        This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".

        func MarshalPKCS8PrivateKey

        func MarshalPKCS8PrivateKey(key any) ([]byte, error)

        MarshalPKCS8PrivateKey converts a private key to PKCS #8, ASN.1 DER form.

        The following key types are currently supported: *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey (not a pointer), and *ecdh.PrivateKey. Unsupported key types result in an error.

        This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".

        func MarshalPKIXPublicKey

        func MarshalPKIXPublicKey(pub any) ([]byte, error)

        MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form. The encoded public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).

        The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey (not a pointer), and *ecdh.PublicKey. Unsupported key types result in an error.

        This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".

        func ParseCRL

        func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error)

        ParseCRL parses a CRL from the given bytes. It's often the case that PEM encoded CRLs will appear where they should be DER encoded, so this function will transparently handle PEM encoding as long as there isn't any leading garbage.

        Deprecated: Use ParseRevocationList instead.

        func ParseDERCRL

        func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error)

        ParseDERCRL parses a DER encoded CRL from the given bytes.

        Deprecated: Use ParseRevocationList instead.

        func ParseECPrivateKey

        func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)

        ParseECPrivateKey parses an EC private key in SEC 1, ASN.1 DER form.

        This kind of key is commonly encoded in PEM blocks of type "EC PRIVATE KEY".

        func ParsePKCS1PrivateKey

        func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)

        ParsePKCS1PrivateKey parses an RSA private key in PKCS #1, ASN.1 DER form.

        This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY".

        func ParsePKCS1PublicKey

        func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error)

        ParsePKCS1PublicKey parses an RSA public key in PKCS #1, ASN.1 DER form.

        This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".

        func ParsePKCS8PrivateKey

        func ParsePKCS8PrivateKey(der []byte) (key any, err error)

        ParsePKCS8PrivateKey parses an unencrypted private key in PKCS #8, ASN.1 DER form.

        It returns a *rsa.PrivateKey, an *ecdsa.PrivateKey, an ed25519.PrivateKey (not a pointer), or an *ecdh.PrivateKey (for X25519). More types might be supported in the future.

        This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".

        func ParsePKIXPublicKey

        func ParsePKIXPublicKey(derBytes []byte) (pub any, err error)

        ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. The encoded public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).

        It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey (not a pointer), or *ecdh.PublicKey (for X25519). More types might be supported in the future.

        This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".

        Example

        Code:

        const pubPEM = `
        -----BEGIN PUBLIC KEY-----
        MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlRuRnThUjU8/prwYxbty
        WPT9pURI3lbsKMiB6Fn/VHOKE13p4D8xgOCADpdRagdT6n4etr9atzDKUSvpMtR3
        CP5noNc97WiNCggBjVWhs7szEe8ugyqF23XwpHQ6uV1LKH50m92MbOWfCtjU9p/x
        qhNpQQ1AZhqNy5Gevap5k8XzRmjSldNAFZMY7Yv3Gi+nyCwGwpVtBUwhuLzgNFK/
        yDtw2WcWmUU7NuC8Q6MWvPebxVtCfVp/iQU6q60yyt6aGOBkhAX0LpKAEhKidixY
        nP9PNVBvxgu3XZ4P36gZV6+ummKdBVnc3NqwBLu5+CcdRdusmHPHd5pHf4/38Z3/
        6qU2a/fPvWzceVTEgZ47QjFMTCTmCwNt29cvi7zZeQzjtwQgn4ipN9NibRH/Ax/q
        TbIzHfrJ1xa2RteWSdFjwtxi9C20HUkjXSeI4YlzQMH0fPX6KCE7aVePTOnB69I/
        a9/q96DiXZajwlpq3wFctrs1oXqBp5DVrCIj8hU2wNgB7LtQ1mCtsYz//heai0K9
        PhE4X6hiE0YmeAZjR0uHl8M/5aW9xCoJ72+12kKpWAa0SFRWLy6FejNYCYpkupVJ
        yecLk/4L1W0l6jQQZnWErXZYe0PNFcmwGXy1Rep83kfBRNKRy5tvocalLlwXLdUk
        AIU+2GKjyT3iMuzZxxFxPFMCAwEAAQ==
        -----END PUBLIC KEY-----`
        
        block, _ := pem.Decode([]byte(pubPEM))
        if block == nil {
            panic("failed to parse PEM block containing the public key")
        }
        
        pub, err := x509.ParsePKIXPublicKey(block.Bytes)
        if err != nil {
            panic("failed to parse DER encoded public key: " + err.Error())
        }
        
        switch pub := pub.(type) {
        case *rsa.PublicKey:
            fmt.Println("pub is of type RSA:", pub)
        case *dsa.PublicKey:
            fmt.Println("pub is of type DSA:", pub)
        case *ecdsa.PublicKey:
            fmt.Println("pub is of type ECDSA:", pub)
        case ed25519.PublicKey:
            fmt.Println("pub is of type Ed25519:", pub)
        default:
            panic("unknown type of public key")
        }
        

        func SetFallbackRoots

        func SetFallbackRoots(roots *CertPool)

        SetFallbackRoots sets the roots to use during certificate verification, if no custom roots are specified and a platform verifier or a system certificate pool is not available (for instance in a container which does not have a root certificate bundle). SetFallbackRoots will panic if roots is nil.

        SetFallbackRoots may only be called once, if called multiple times it will panic.

        The fallback behavior can be forced on all platforms, even when there is a system certificate pool, by setting GODEBUG=x509usefallbackroots=1 (note that on Windows and macOS this will disable usage of the platform verification APIs and cause the pure Go verifier to be used). Setting x509usefallbackroots=1 without calling SetFallbackRoots has no effect.

        type CertPool

        CertPool is a set of certificates.

        type CertPool struct {
            // contains filtered or unexported fields
        }
        

        func NewCertPool

        func NewCertPool() *CertPool

        NewCertPool returns a new, empty CertPool.

        func SystemCertPool

        func SystemCertPool() (*CertPool, error)

        SystemCertPool returns a copy of the system cert pool.

        On Unix systems other than macOS the environment variables SSL_CERT_FILE and SSL_CERT_DIR can be used to override the system default locations for the SSL certificate file and SSL certificate files directory, respectively. The latter can be a colon-separated list.

        Any mutations to the returned pool are not written to disk and do not affect any other pool returned by SystemCertPool.

        New changes in the system cert pool might not be reflected in subsequent calls.

        func (*CertPool) AddCert

        func (s *CertPool) AddCert(cert *Certificate)

        AddCert adds a certificate to a pool.

        func (*CertPool) AddCertWithConstraint

        func (s *CertPool) AddCertWithConstraint(cert *Certificate, constraint func([]*Certificate) error)

        AddCertWithConstraint adds a certificate to the pool with the additional constraint. When Certificate.Verify builds a chain which is rooted by cert, it will additionally pass the whole chain to constraint to determine its validity. If constraint returns a non-nil error, the chain will be discarded. constraint may be called concurrently from multiple goroutines.

        func (*CertPool) AppendCertsFromPEM

        func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)

        AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. It appends any certificates found to s and reports whether any certificates were successfully parsed.

        On many Linux systems, /etc/ssl/cert.pem will contain the system wide set of root CAs in a format suitable for this function.

        func (*CertPool) Clone

        func (s *CertPool) Clone() *CertPool

        Clone returns a copy of s.

        func (*CertPool) Equal

        func (s *CertPool) Equal(other *CertPool) bool

        Equal reports whether s and other are equal.

        func (*CertPool) Subjects

        func (s *CertPool) Subjects() [][]byte

        Subjects returns a list of the DER-encoded subjects of all of the certificates in the pool.

        Deprecated: if s was returned by SystemCertPool, Subjects will not include the system roots.

        type Certificate

        A Certificate represents an X.509 certificate.

        type Certificate struct {
            Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
            RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
            RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
            RawSubject              []byte // DER encoded Subject
            RawIssuer               []byte // DER encoded Issuer
        
            Signature          []byte
            SignatureAlgorithm SignatureAlgorithm
        
            PublicKeyAlgorithm PublicKeyAlgorithm
            PublicKey          any
        
            Version             int
            SerialNumber        *big.Int
            Issuer              pkix.Name
            Subject             pkix.Name
            NotBefore, NotAfter time.Time // Validity bounds.
            KeyUsage            KeyUsage
        
            // Extensions contains raw X.509 extensions. When parsing certificates,
            // this can be used to extract non-critical extensions that are not
            // parsed by this package. When marshaling certificates, the Extensions
            // field is ignored, see ExtraExtensions.
            Extensions []pkix.Extension
        
            // ExtraExtensions contains extensions to be copied, raw, into any
            // marshaled certificates. Values override any extensions that would
            // otherwise be produced based on the other fields. The ExtraExtensions
            // field is not populated when parsing certificates, see Extensions.
            ExtraExtensions []pkix.Extension
        
            // UnhandledCriticalExtensions contains a list of extension IDs that
            // were not (fully) processed when parsing. Verify will fail if this
            // slice is non-empty, unless verification is delegated to an OS
            // library which understands all the critical extensions.
            //
            // Users can access these extensions using Extensions and can remove
            // elements from this slice if they believe that they have been
            // handled.
            UnhandledCriticalExtensions []asn1.ObjectIdentifier
        
            ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
            UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
        
            // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
            // and MaxPathLenZero are valid.
            BasicConstraintsValid bool
            IsCA                  bool
        
            // MaxPathLen and MaxPathLenZero indicate the presence and
            // value of the BasicConstraints' "pathLenConstraint".
            //
            // When parsing a certificate, a positive non-zero MaxPathLen
            // means that the field was specified, -1 means it was unset,
            // and MaxPathLenZero being true mean that the field was
            // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
            // should be treated equivalent to -1 (unset).
            //
            // When generating a certificate, an unset pathLenConstraint
            // can be requested with either MaxPathLen == -1 or using the
            // zero value for both MaxPathLen and MaxPathLenZero.
            MaxPathLen int
            // MaxPathLenZero indicates that BasicConstraintsValid==true
            // and MaxPathLen==0 should be interpreted as an actual
            // maximum path length of zero. Otherwise, that combination is
            // interpreted as MaxPathLen not being set.
            MaxPathLenZero bool
        
            SubjectKeyId   []byte
            AuthorityKeyId []byte
        
            // RFC 5280, 4.2.2.1 (Authority Information Access)
            OCSPServer            []string
            IssuingCertificateURL []string
        
            // Subject Alternate Name values. (Note that these values may not be valid
            // if invalid values were contained within a parsed certificate. For
            // example, an element of DNSNames may not be a valid DNS domain name.)
            DNSNames       []string
            EmailAddresses []string
            IPAddresses    []net.IP
            URIs           []*url.URL
        
            // Name constraints
            PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
            PermittedDNSDomains         []string
            ExcludedDNSDomains          []string
            PermittedIPRanges           []*net.IPNet
            ExcludedIPRanges            []*net.IPNet
            PermittedEmailAddresses     []string
            ExcludedEmailAddresses      []string
            PermittedURIDomains         []string
            ExcludedURIDomains          []string
        
            // CRL Distribution Points
            CRLDistributionPoints []string
        
            // PolicyIdentifiers contains asn1.ObjectIdentifiers, the components
            // of which are limited to int32. If a certificate contains a policy which
            // cannot be represented by asn1.ObjectIdentifier, it will not be included in
            // PolicyIdentifiers, but will be present in Policies, which contains all parsed
            // policy OIDs.
            PolicyIdentifiers []asn1.ObjectIdentifier
        
            // Policies contains all policy identifiers included in the certificate.
            // In Go 1.22, encoding/gob cannot handle and ignores this field.
            Policies []OID
        }
        

        func ParseCertificate

        func ParseCertificate(der []byte) (*Certificate, error)

        ParseCertificate parses a single certificate from the given ASN.1 DER data.

        func ParseCertificates

        func ParseCertificates(der []byte) ([]*Certificate, error)

        ParseCertificates parses one or more certificates from the given ASN.1 DER data. The certificates must be concatenated with no intermediate padding.

        func (*Certificate) CheckCRLSignature

        func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error

        CheckCRLSignature checks that the signature in crl is from c.

        Deprecated: Use RevocationList.CheckSignatureFrom instead.

        func (*Certificate) CheckSignature

        func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error

        CheckSignature verifies that signature is a valid signature over signed from c's public key.

        This is a low-level API that performs no validity checks on the certificate.

        MD5WithRSA signatures are rejected, while SHA1WithRSA and ECDSAWithSHA1 signatures are currently accepted.

        func (*Certificate) CheckSignatureFrom

        func (c *Certificate) CheckSignatureFrom(parent *Certificate) error

        CheckSignatureFrom verifies that the signature on c is a valid signature from parent.

        This is a low-level API that performs very limited checks, and not a full path verifier. Most users should use Certificate.Verify instead.

        func (*Certificate) CreateCRL

        func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error)

        CreateCRL returns a DER encoded CRL, signed by this Certificate, that contains the given list of revoked certificates.

        Deprecated: this method does not generate an RFC 5280 conformant X.509 v2 CRL. To generate a standards compliant CRL, use CreateRevocationList instead.

        func (*Certificate) Equal

        func (c *Certificate) Equal(other *Certificate) bool

        func (*Certificate) Verify

        func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)

        Verify attempts to verify c by building one or more chains from c to a certificate in opts.Roots, using certificates in opts.Intermediates if needed. If successful, it returns one or more chains where the first element of the chain is c and the last element is from opts.Roots.

        If opts.Roots is nil, the platform verifier might be used, and verification details might differ from what is described below. If system roots are unavailable the returned error will be of type SystemRootsError.

        Name constraints in the intermediates will be applied to all names claimed in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim example.com if an intermediate doesn't permit it, even if example.com is not the name being validated. Note that DirectoryName constraints are not supported.

        Name constraint validation follows the rules from RFC 5280, with the addition that DNS name constraints may use the leading period format defined for emails and URIs. When a constraint has a leading period it indicates that at least one additional label must be prepended to the constrained name to be considered valid.

        Extended Key Usage values are enforced nested down a chain, so an intermediate or root that enumerates EKUs prevents a leaf from asserting an EKU not in that list. (While this is not specified, it is common practice in order to limit the types of certificates a CA can issue.)

        Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported, and will not be used to build chains.

        Certificates other than c in the returned chains should not be modified.

        WARNING: this function doesn't do any revocation checking.

        Example

        Code:

        // Verifying with a custom list of root certificates.
        
        const rootPEM = `
        -----BEGIN CERTIFICATE-----
        MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
        MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
        YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
        EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
        bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
        AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP
        VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv
        h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE
        ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ
        EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC
        DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7
        qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD
        VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g
        K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI
        KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n
        ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
        BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
        /iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
        zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
        HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
        WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
        yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
        -----END CERTIFICATE-----`
        
        const certPEM = `
        -----BEGIN CERTIFICATE-----
        MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE
        BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl
        cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMTI5MTMyNzQzWhcNMTQwNTI5MDAwMDAw
        WjBpMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN
        TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEYMBYGA1UEAwwPbWFp
        bC5nb29nbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfRrObuSW5T7q
        5CnSEqefEmtH4CCv6+5EckuriNr1CjfVvqzwfAhopXkLrq45EQm8vkmf7W96XJhC
        7ZM0dYi1/qOCAU8wggFLMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAa
        BgNVHREEEzARgg9tYWlsLmdvb2dsZS5jb20wCwYDVR0PBAQDAgeAMGgGCCsGAQUF
        BwEBBFwwWjArBggrBgEFBQcwAoYfaHR0cDovL3BraS5nb29nbGUuY29tL0dJQUcy
        LmNydDArBggrBgEFBQcwAYYfaHR0cDovL2NsaWVudHMxLmdvb2dsZS5jb20vb2Nz
        cDAdBgNVHQ4EFgQUiJxtimAuTfwb+aUtBn5UYKreKvMwDAYDVR0TAQH/BAIwADAf
        BgNVHSMEGDAWgBRK3QYWG7z2aLV29YG2u2IaulqBLzAXBgNVHSAEEDAOMAwGCisG
        AQQB1nkCBQEwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3BraS5nb29nbGUuY29t
        L0dJQUcyLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAH6RYHxHdcGpMpFE3oxDoFnP+
        gtuBCHan2yE2GRbJ2Cw8Lw0MmuKqHlf9RSeYfd3BXeKkj1qO6TVKwCh+0HdZk283
        TZZyzmEOyclm3UGFYe82P/iDFt+CeQ3NpmBg+GoaVCuWAARJN/KfglbLyyYygcQq
        0SgeDh8dRKUiaW3HQSoYvTvdTuqzwK4CXsr3b5/dAOY8uMuG/IAR3FgwTbZ1dtoW
        RvOTa8hYiU6A475WuZKyEHcwnGYe57u2I2KbMgcKjPniocj4QzgYsVAVKW3IwaOh
        yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
        -----END CERTIFICATE-----`
        
        // First, create the set of root certificates. For this example we only
        // have one. It's also possible to omit this in order to use the
        // default root set of the current operating system.
        roots := x509.NewCertPool()
        ok := roots.AppendCertsFromPEM([]byte(rootPEM))
        if !ok {
            panic("failed to parse root certificate")
        }
        
        block, _ := pem.Decode([]byte(certPEM))
        if block == nil {
            panic("failed to parse certificate PEM")
        }
        cert, err := x509.ParseCertificate(block.Bytes)
        if err != nil {
            panic("failed to parse certificate: " + err.Error())
        }
        
        opts := x509.VerifyOptions{
            DNSName: "mail.google.com",
            Roots:   roots,
        }
        
        if _, err := cert.Verify(opts); err != nil {
            panic("failed to verify certificate: " + err.Error())
        }
        

        func (*Certificate) VerifyHostname

        func (c *Certificate) VerifyHostname(h string) error

        VerifyHostname returns nil if c is a valid certificate for the named host. Otherwise it returns an error describing the mismatch.

        IP addresses can be optionally enclosed in square brackets and are checked against the IPAddresses field. Other names are checked case insensitively against the DNSNames field. If the names are valid hostnames, the certificate fields can have a wildcard as the complete left-most label (e.g. *.example.com).

        Note that the legacy Common Name field is ignored.

        type CertificateInvalidError

        CertificateInvalidError results when an odd error occurs. Users of this library probably want to handle all these errors uniformly.

        type CertificateInvalidError struct {
            Cert   *Certificate
            Reason InvalidReason
            Detail string
        }
        

        func (CertificateInvalidError) Error

        func (e CertificateInvalidError) Error() string

        type CertificateRequest

        CertificateRequest represents a PKCS #10, certificate signature request.

        type CertificateRequest struct {
            Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
            RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
            RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
            RawSubject               []byte // DER encoded Subject.
        
            Version            int
            Signature          []byte
            SignatureAlgorithm SignatureAlgorithm
        
            PublicKeyAlgorithm PublicKeyAlgorithm
            PublicKey          any
        
            Subject pkix.Name
        
            // Attributes contains the CSR attributes that can parse as
            // pkix.AttributeTypeAndValueSET.
            //
            // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
            // generating the requestedExtensions attribute.
            Attributes []pkix.AttributeTypeAndValueSET
        
            // Extensions contains all requested extensions, in raw form. When parsing
            // CSRs, this can be used to extract extensions that are not parsed by this
            // package.
            Extensions []pkix.Extension
        
            // ExtraExtensions contains extensions to be copied, raw, into any CSR
            // marshaled by CreateCertificateRequest. Values override any extensions
            // that would otherwise be produced based on the other fields but are
            // overridden by any extensions specified in Attributes.
            //
            // The ExtraExtensions field is not populated by ParseCertificateRequest,
            // see Extensions instead.
            ExtraExtensions []pkix.Extension
        
            // Subject Alternate Name values.
            DNSNames       []string
            EmailAddresses []string
            IPAddresses    []net.IP
            URIs           []*url.URL
        }
        

        func ParseCertificateRequest

        func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)

        ParseCertificateRequest parses a single certificate request from the given ASN.1 DER data.

        func (*CertificateRequest) CheckSignature

        func (c *CertificateRequest) CheckSignature() error

        CheckSignature reports whether the signature on c is valid.

        type ConstraintViolationError

        ConstraintViolationError results when a requested usage is not permitted by a certificate. For example: checking a signature when the public key isn't a certificate signing key.

        type ConstraintViolationError struct{}
        

        func (ConstraintViolationError) Error

        func (ConstraintViolationError) Error() string

        type ExtKeyUsage

        ExtKeyUsage represents an extended set of actions that are valid for a given key. Each of the ExtKeyUsage* constants define a unique action.

        type ExtKeyUsage int
        const (
            ExtKeyUsageAny ExtKeyUsage = iota
            ExtKeyUsageServerAuth
            ExtKeyUsageClientAuth
            ExtKeyUsageCodeSigning
            ExtKeyUsageEmailProtection
            ExtKeyUsageIPSECEndSystem
            ExtKeyUsageIPSECTunnel
            ExtKeyUsageIPSECUser
            ExtKeyUsageTimeStamping
            ExtKeyUsageOCSPSigning
            ExtKeyUsageMicrosoftServerGatedCrypto
            ExtKeyUsageNetscapeServerGatedCrypto
            ExtKeyUsageMicrosoftCommercialCodeSigning
            ExtKeyUsageMicrosoftKernelCodeSigning
        )

        type HostnameError

        HostnameError results when the set of authorized names doesn't match the requested name.

        type HostnameError struct {
            Certificate *Certificate
            Host        string
        }
        

        func (HostnameError) Error

        func (h HostnameError) Error() string

        type InsecureAlgorithmError

        An InsecureAlgorithmError indicates that the SignatureAlgorithm used to generate the signature is not secure, and the signature has been rejected.

        To temporarily restore support for SHA-1 signatures, include the value "x509sha1=1" in the GODEBUG environment variable. Note that this option will be removed in a future release.

        type InsecureAlgorithmError SignatureAlgorithm

        func (InsecureAlgorithmError) Error

        func (e InsecureAlgorithmError) Error() string

        type InvalidReason

        type InvalidReason int
        const (
            // NotAuthorizedToSign results when a certificate is signed by another
            // which isn't marked as a CA certificate.
            NotAuthorizedToSign InvalidReason = iota
            // Expired results when a certificate has expired, based on the time
            // given in the VerifyOptions.
            Expired
            // CANotAuthorizedForThisName results when an intermediate or root
            // certificate has a name constraint which doesn't permit a DNS or
            // other name (including IP address) in the leaf certificate.
            CANotAuthorizedForThisName
            // TooManyIntermediates results when a path length constraint is
            // violated.
            TooManyIntermediates
            // IncompatibleUsage results when the certificate's key usage indicates
            // that it may only be used for a different purpose.
            IncompatibleUsage
            // NameMismatch results when the subject name of a parent certificate
            // does not match the issuer name in the child.
            NameMismatch
            // NameConstraintsWithoutSANs is a legacy error and is no longer returned.
            NameConstraintsWithoutSANs
            // UnconstrainedName results when a CA certificate contains permitted
            // name constraints, but leaf certificate contains a name of an
            // unsupported or unconstrained type.
            UnconstrainedName
            // TooManyConstraints results when the number of comparison operations
            // needed to check a certificate exceeds the limit set by
            // VerifyOptions.MaxConstraintComparisions. This limit exists to
            // prevent pathological certificates can consuming excessive amounts of
            // CPU time to verify.
            TooManyConstraints
            // CANotAuthorizedForExtKeyUsage results when an intermediate or root
            // certificate does not permit a requested extended key usage.
            CANotAuthorizedForExtKeyUsage
        )

        type KeyUsage

        KeyUsage represents the set of actions that are valid for a given key. It's a bitmap of the KeyUsage* constants.

        type KeyUsage int
        const (
            KeyUsageDigitalSignature KeyUsage = 1 << iota
            KeyUsageContentCommitment
            KeyUsageKeyEncipherment
            KeyUsageDataEncipherment
            KeyUsageKeyAgreement
            KeyUsageCertSign
            KeyUsageCRLSign
            KeyUsageEncipherOnly
            KeyUsageDecipherOnly
        )

        type OID

        An OID represents an ASN.1 OBJECT IDENTIFIER.

        type OID struct {
            // contains filtered or unexported fields
        }
        

        func OIDFromInts

        func OIDFromInts(oid []uint64) (OID, error)

        OIDFromInts creates a new OID using ints, each integer is a separate component.

        func (OID) Equal

        func (oid OID) Equal(other OID) bool

        Equal returns true when oid and other represents the same Object Identifier.

        func (OID) EqualASN1OID

        func (oid OID) EqualASN1OID(other asn1.ObjectIdentifier) bool

        EqualASN1OID returns whether an OID equals an asn1.ObjectIdentifier. If asn1.ObjectIdentifier cannot represent the OID specified by oid, because a component of OID requires more than 31 bits, it returns false.

        func (OID) String

        func (oid OID) String() string

        Strings returns the string representation of the Object Identifier.

        type PEMCipher

        type PEMCipher int

        Possible values for the EncryptPEMBlock encryption algorithm.

        const (
            PEMCipherDES PEMCipher
            PEMCipher3DES
            PEMCipherAES128
            PEMCipherAES192
            PEMCipherAES256
        )

        type PublicKeyAlgorithm

        type PublicKeyAlgorithm int
        const (
            UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
            RSA
            DSA // Only supported for parsing.
            ECDSA
            Ed25519
        )

        func (PublicKeyAlgorithm) String

        func (algo PublicKeyAlgorithm) String() string

        type RevocationList

        RevocationList represents a Certificate Revocation List (CRL) as specified by RFC 5280.

        type RevocationList struct {
            // Raw contains the complete ASN.1 DER content of the CRL (tbsCertList,
            // signatureAlgorithm, and signatureValue.)
            Raw []byte
            // RawTBSRevocationList contains just the tbsCertList portion of the ASN.1
            // DER.
            RawTBSRevocationList []byte
            // RawIssuer contains the DER encoded Issuer.
            RawIssuer []byte
        
            // Issuer contains the DN of the issuing certificate.
            Issuer pkix.Name
            // AuthorityKeyId is used to identify the public key associated with the
            // issuing certificate. It is populated from the authorityKeyIdentifier
            // extension when parsing a CRL. It is ignored when creating a CRL; the
            // extension is populated from the issuing certificate itself.
            AuthorityKeyId []byte
        
            Signature []byte
            // SignatureAlgorithm is used to determine the signature algorithm to be
            // used when signing the CRL. If 0 the default algorithm for the signing
            // key will be used.
            SignatureAlgorithm SignatureAlgorithm
        
            // RevokedCertificateEntries represents the revokedCertificates sequence in
            // the CRL. It is used when creating a CRL and also populated when parsing a
            // CRL. When creating a CRL, it may be empty or nil, in which case the
            // revokedCertificates ASN.1 sequence will be omitted from the CRL entirely.
            RevokedCertificateEntries []RevocationListEntry
        
            // RevokedCertificates is used to populate the revokedCertificates
            // sequence in the CRL if RevokedCertificateEntries is empty. It may be empty
            // or nil, in which case an empty CRL will be created.
            //
            // Deprecated: Use RevokedCertificateEntries instead.
            RevokedCertificates []pkix.RevokedCertificate
        
            // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
            // which should be a monotonically increasing sequence number for a given
            // CRL scope and CRL issuer. It is also populated from the cRLNumber
            // extension when parsing a CRL.
            Number *big.Int
        
            // ThisUpdate is used to populate the thisUpdate field in the CRL, which
            // indicates the issuance date of the CRL.
            ThisUpdate time.Time
            // NextUpdate is used to populate the nextUpdate field in the CRL, which
            // indicates the date by which the next CRL will be issued. NextUpdate
            // must be greater than ThisUpdate.
            NextUpdate time.Time
        
            // Extensions contains raw X.509 extensions. When creating a CRL,
            // the Extensions field is ignored, see ExtraExtensions.
            Extensions []pkix.Extension
        
            // ExtraExtensions contains any additional extensions to add directly to
            // the CRL.
            ExtraExtensions []pkix.Extension
        }
        

        func ParseRevocationList

        func ParseRevocationList(der []byte) (*RevocationList, error)

        ParseRevocationList parses a X509 v2 Certificate Revocation List from the given ASN.1 DER data.

        func (*RevocationList) CheckSignatureFrom

        func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error

        CheckSignatureFrom verifies that the signature on rl is a valid signature from issuer.

        type RevocationListEntry

        RevocationListEntry represents an entry in the revokedCertificates sequence of a CRL.

        type RevocationListEntry struct {
            // Raw contains the raw bytes of the revokedCertificates entry. It is set when
            // parsing a CRL; it is ignored when generating a CRL.
            Raw []byte
        
            // SerialNumber represents the serial number of a revoked certificate. It is
            // both used when creating a CRL and populated when parsing a CRL. It must not
            // be nil.
            SerialNumber *big.Int
            // RevocationTime represents the time at which the certificate was revoked. It
            // is both used when creating a CRL and populated when parsing a CRL. It must
            // not be the zero time.
            RevocationTime time.Time
            // ReasonCode represents the reason for revocation, using the integer enum
            // values specified in RFC 5280 Section 5.3.1. When creating a CRL, the zero
            // value will result in the reasonCode extension being omitted. When parsing a
            // CRL, the zero value may represent either the reasonCode extension being
            // absent (which implies the default revocation reason of 0/Unspecified), or
            // it may represent the reasonCode extension being present and explicitly
            // containing a value of 0/Unspecified (which should not happen according to
            // the DER encoding rules, but can and does happen anyway).
            ReasonCode int
        
            // Extensions contains raw X.509 extensions. When parsing CRL entries,
            // this can be used to extract non-critical extensions that are not
            // parsed by this package. When marshaling CRL entries, the Extensions
            // field is ignored, see ExtraExtensions.
            Extensions []pkix.Extension
            // ExtraExtensions contains extensions to be copied, raw, into any
            // marshaled CRL entries. Values override any extensions that would
            // otherwise be produced based on the other fields. The ExtraExtensions
            // field is not populated when parsing CRL entries, see Extensions.
            ExtraExtensions []pkix.Extension
        }
        

        type SignatureAlgorithm

        type SignatureAlgorithm int
        const (
            UnknownSignatureAlgorithm SignatureAlgorithm = iota
        
            MD2WithRSA  // Unsupported.
            MD5WithRSA  // Only supported for signing, not verification.
            SHA1WithRSA // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
            SHA256WithRSA
            SHA384WithRSA
            SHA512WithRSA
            DSAWithSHA1   // Unsupported.
            DSAWithSHA256 // Unsupported.
            ECDSAWithSHA1 // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
            ECDSAWithSHA256
            ECDSAWithSHA384
            ECDSAWithSHA512
            SHA256WithRSAPSS
            SHA384WithRSAPSS
            SHA512WithRSAPSS
            PureEd25519
        )

        func (SignatureAlgorithm) String

        func (algo SignatureAlgorithm) String() string

        type SystemRootsError

        SystemRootsError results when we fail to load the system root certificates.

        type SystemRootsError struct {
            Err error
        }
        

        func (SystemRootsError) Error

        func (se SystemRootsError) Error() string

        func (SystemRootsError) Unwrap

        func (se SystemRootsError) Unwrap() error

        type UnhandledCriticalExtension

        type UnhandledCriticalExtension struct{}
        

        func (UnhandledCriticalExtension) Error

        func (h UnhandledCriticalExtension) Error() string

        type UnknownAuthorityError

        UnknownAuthorityError results when the certificate issuer is unknown

        type UnknownAuthorityError struct {
            Cert *Certificate
            // contains filtered or unexported fields
        }
        

        func (UnknownAuthorityError) Error

        func (e UnknownAuthorityError) Error() string

        type VerifyOptions

        VerifyOptions contains parameters for Certificate.Verify.

        type VerifyOptions struct {
            // DNSName, if set, is checked against the leaf certificate with
            // Certificate.VerifyHostname or the platform verifier.
            DNSName string
        
            // Intermediates is an optional pool of certificates that are not trust
            // anchors, but can be used to form a chain from the leaf certificate to a
            // root certificate.
            Intermediates *CertPool
            // Roots is the set of trusted root certificates the leaf certificate needs
            // to chain up to. If nil, the system roots or the platform verifier are used.
            Roots *CertPool
        
            // CurrentTime is used to check the validity of all certificates in the
            // chain. If zero, the current time is used.
            CurrentTime time.Time
        
            // KeyUsages specifies which Extended Key Usage values are acceptable. A
            // chain is accepted if it allows any of the listed values. An empty list
            // means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
            KeyUsages []ExtKeyUsage
        
            // MaxConstraintComparisions is the maximum number of comparisons to
            // perform when checking a given certificate's name constraints. If
            // zero, a sensible default is used. This limit prevents pathological
            // certificates from consuming excessive amounts of CPU time when
            // validating. It does not apply to the platform verifier.
            MaxConstraintComparisions int
        }
        

        Subdirectories

        Name Synopsis
        ..
        pkix Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.
        pkix - Go Documentation Server
        ...

        Package pkix

        import "crypto/x509/pkix"
        Overview
        Index

        Overview ▾

        Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.

        type AlgorithmIdentifier

        AlgorithmIdentifier represents the ASN.1 structure of the same name. See RFC 5280, section 4.1.1.2.

        type AlgorithmIdentifier struct {
            Algorithm  asn1.ObjectIdentifier
            Parameters asn1.RawValue `asn1:"optional"`
        }
        

        type AttributeTypeAndValue

        AttributeTypeAndValue mirrors the ASN.1 structure of the same name in RFC 5280, Section 4.1.2.4.

        type AttributeTypeAndValue struct {
            Type  asn1.ObjectIdentifier
            Value any
        }
        

        type AttributeTypeAndValueSET

        AttributeTypeAndValueSET represents a set of ASN.1 sequences of AttributeTypeAndValue sequences from RFC 2986 (PKCS #10).

        type AttributeTypeAndValueSET struct {
            Type  asn1.ObjectIdentifier
            Value [][]AttributeTypeAndValue `asn1:"set"`
        }
        

        type CertificateList

        CertificateList represents the ASN.1 structure of the same name. See RFC 5280, section 5.1. Use Certificate.CheckCRLSignature to verify the signature.

        Deprecated: x509.RevocationList should be used instead.

        type CertificateList struct {
            TBSCertList        TBSCertificateList
            SignatureAlgorithm AlgorithmIdentifier
            SignatureValue     asn1.BitString
        }
        

        func (*CertificateList) HasExpired

        func (certList *CertificateList) HasExpired(now time.Time) bool

        HasExpired reports whether certList should have been updated by now.

        type Extension

        Extension represents the ASN.1 structure of the same name. See RFC 5280, section 4.2.

        type Extension struct {
            Id       asn1.ObjectIdentifier
            Critical bool `asn1:"optional"`
            Value    []byte
        }
        

        type Name

        Name represents an X.509 distinguished name. This only includes the common elements of a DN. Note that Name is only an approximation of the X.509 structure. If an accurate representation is needed, asn1.Unmarshal the raw subject or issuer as an RDNSequence.

        type Name struct {
            Country, Organization, OrganizationalUnit []string
            Locality, Province                        []string
            StreetAddress, PostalCode                 []string
            SerialNumber, CommonName                  string
        
            // Names contains all parsed attributes. When parsing distinguished names,
            // this can be used to extract non-standard attributes that are not parsed
            // by this package. When marshaling to RDNSequences, the Names field is
            // ignored, see ExtraNames.
            Names []AttributeTypeAndValue
        
            // ExtraNames contains attributes to be copied, raw, into any marshaled
            // distinguished names. Values override any attributes with the same OID.
            // The ExtraNames field is not populated when parsing, see Names.
            ExtraNames []AttributeTypeAndValue
        }
        

        func (*Name) FillFromRDNSequence

        func (n *Name) FillFromRDNSequence(rdns *RDNSequence)

        FillFromRDNSequence populates n from the provided RDNSequence. Multi-entry RDNs are flattened, all entries are added to the relevant n fields, and the grouping is not preserved.

        func (Name) String

        func (n Name) String() string

        String returns the string form of n, roughly following the RFC 2253 Distinguished Names syntax.

        func (Name) ToRDNSequence

        func (n Name) ToRDNSequence() (ret RDNSequence)

        ToRDNSequence converts n into a single RDNSequence. The following attributes are encoded as multi-value RDNs:

        • Country
        • Organization
        • OrganizationalUnit
        • Locality
        • Province
        • StreetAddress
        • PostalCode

        Each ExtraNames entry is encoded as an individual RDN.

        type RDNSequence

        type RDNSequence []RelativeDistinguishedNameSET

        func (RDNSequence) String

        func (r RDNSequence) String() string

        String returns a string representation of the sequence r, roughly following the RFC 2253 Distinguished Names syntax.

        type RelativeDistinguishedNameSET

        type RelativeDistinguishedNameSET []AttributeTypeAndValue

        type RevokedCertificate

        RevokedCertificate represents the ASN.1 structure of the same name. See RFC 5280, section 5.1.

        type RevokedCertificate struct {
            SerialNumber   *big.Int
            RevocationTime time.Time
            Extensions     []Extension `asn1:"optional"`
        }
        

        type TBSCertificateList

        TBSCertificateList represents the ASN.1 structure of the same name. See RFC 5280, section 5.1.

        Deprecated: x509.RevocationList should be used instead.

        type TBSCertificateList struct {
            Raw                 asn1.RawContent
            Version             int `asn1:"optional,default:0"`
            Signature           AlgorithmIdentifier
            Issuer              RDNSequence
            ThisUpdate          time.Time
            NextUpdate          time.Time            `asn1:"optional"`
            RevokedCertificates []RevokedCertificate `asn1:"optional"`
            Extensions          []Extension          `asn1:"tag:0,optional,explicit"`
        }
        
        /src/database - Go Documentation Server
        ...

        Directory /src/database

        Name Synopsis
        ..
        sql Package sql provides a generic interface around SQL (or SQL-like) databases.
        driver Package driver defines interfaces to be implemented by database drivers as used by package sql.
        sql - Go Documentation Server
        ...

        Package sql

        import "database/sql"
        Overview
        Index
        Examples
        Subdirectories

        Overview ▾

        Package sql provides a generic interface around SQL (or SQL-like) databases.

        The sql package must be used in conjunction with a database driver. See https://golang.org/s/sqldrivers for a list of drivers.

        Drivers that do not support context cancellation will not return until after the query is completed.

        For usage examples, see the wiki page at https://golang.org/s/sqlwiki.

        Example (OpenDBCLI)

        Code:

        package sql_test
        
        import (
            "context"
            "database/sql"
            "flag"
            "log"
            "os"
            "os/signal"
            "time"
        )
        
        var pool *sql.DB // Database connection pool.
        
        func Example_openDBCLI() {
            id := flag.Int64("id", 0, "person ID to find")
            dsn := flag.String("dsn", os.Getenv("DSN"), "connection data source name")
            flag.Parse()
        
            if len(*dsn) == 0 {
                log.Fatal("missing dsn flag")
            }
            if *id == 0 {
                log.Fatal("missing person ID")
            }
            var err error
        
            // Opening a driver typically will not attempt to connect to the database.
            pool, err = sql.Open("driver-name", *dsn)
            if err != nil {
                // This will not be a connection error, but a DSN parse error or
                // another initialization error.
                log.Fatal("unable to use data source name", err)
            }
            defer pool.Close()
        
            pool.SetConnMaxLifetime(0)
            pool.SetMaxIdleConns(3)
            pool.SetMaxOpenConns(3)
        
            ctx, stop := context.WithCancel(context.Background())
            defer stop()
        
            appSignal := make(chan os.Signal, 3)
            signal.Notify(appSignal, os.Interrupt)
        
            go func() {
                <-appSignal
                stop()
            }()
        
            Ping(ctx)
        
            Query(ctx, *id)
        }
        
        // Ping the database to verify DSN provided by the user is valid and the
        // server accessible. If the ping fails exit the program with an error.
        func Ping(ctx context.Context) {
            ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
            defer cancel()
        
            if err := pool.PingContext(ctx); err != nil {
                log.Fatalf("unable to connect to database: %v", err)
            }
        }
        
        // Query the database for the information requested and prints the results.
        // If the query fails exit the program with an error.
        func Query(ctx context.Context, id int64) {
            ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
            defer cancel()
        
            var name string
            err := pool.QueryRowContext(ctx, "select p.name from people as p where p.id = :id;", sql.Named("id", id)).Scan(&name)
            if err != nil {
                log.Fatal("unable to execute search query", err)
            }
            log.Println("name=", name)
        }
        

        Example (OpenDBService)

        Code:

        package sql_test
        
        import (
            "context"
            "database/sql"
            "encoding/json"
            "fmt"
            "io"
            "log"
            "net/http"
            "time"
        )
        
        func Example_openDBService() {
            // Opening a driver typically will not attempt to connect to the database.
            db, err := sql.Open("driver-name", "database=test1")
            if err != nil {
                // This will not be a connection error, but a DSN parse error or
                // another initialization error.
                log.Fatal(err)
            }
            db.SetConnMaxLifetime(0)
            db.SetMaxIdleConns(50)
            db.SetMaxOpenConns(50)
        
            s := &Service{db: db}
        
            http.ListenAndServe(":8080", s)
        }
        
        type Service struct {
            db *sql.DB
        }
        
        func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
            db := s.db
            switch r.URL.Path {
            default:
                http.Error(w, "not found", http.StatusNotFound)
                return
            case "/healthz":
                ctx, cancel := context.WithTimeout(r.Context(), 1*time.Second)
                defer cancel()
        
                err := s.db.PingContext(ctx)
                if err != nil {
                    http.Error(w, fmt.Sprintf("db down: %v", err), http.StatusFailedDependency)
                    return
                }
                w.WriteHeader(http.StatusOK)
                return
            case "/quick-action":
                // This is a short SELECT. Use the request context as the base of
                // the context timeout.
                ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
                defer cancel()
        
                id := 5
                org := 10
                var name string
                err := db.QueryRowContext(ctx, `
        select
            p.name
        from
            people as p
            join organization as o on p.organization = o.id
        where
            p.id = :id
            and o.id = :org
        ;`,
                    sql.Named("id", id),
                    sql.Named("org", org),
                ).Scan(&name)
                if err != nil {
                    if err == sql.ErrNoRows {
                        http.Error(w, "not found", http.StatusNotFound)
                        return
                    }
                    http.Error(w, err.Error(), http.StatusInternalServerError)
                    return
                }
                io.WriteString(w, name)
                return
            case "/long-action":
                // This is a long SELECT. Use the request context as the base of
                // the context timeout, but give it some time to finish. If
                // the client cancels before the query is done the query will also
                // be canceled.
                ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
                defer cancel()
        
                var names []string
                rows, err := db.QueryContext(ctx, "select p.name from people as p where p.active = true;")
                if err != nil {
                    http.Error(w, err.Error(), http.StatusInternalServerError)
                    return
                }
        
                for rows.Next() {
                    var name string
                    err = rows.Scan(&name)
                    if err != nil {
                        break
                    }
                    names = append(names, name)
                }
                // Check for errors during rows "Close".
                // This may be more important if multiple statements are executed
                // in a single batch and rows were written as well as read.
                if closeErr := rows.Close(); closeErr != nil {
                    http.Error(w, closeErr.Error(), http.StatusInternalServerError)
                    return
                }
        
                // Check for row scan error.
                if err != nil {
                    http.Error(w, err.Error(), http.StatusInternalServerError)
                    return
                }
        
                // Check for errors during row iteration.
                if err = rows.Err(); err != nil {
                    http.Error(w, err.Error(), http.StatusInternalServerError)
                    return
                }
        
                json.NewEncoder(w).Encode(names)
                return
            case "/async-action":
                // This action has side effects that we want to preserve
                // even if the client cancels the HTTP request part way through.
                // For this we do not use the http request context as a base for
                // the timeout.
                ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
                defer cancel()
        
                var orderRef = "ABC123"
                tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
                _, err = tx.ExecContext(ctx, "stored_proc_name", orderRef)
        
                if err != nil {
                    tx.Rollback()
                    http.Error(w, err.Error(), http.StatusInternalServerError)
                    return
                }
                err = tx.Commit()
                if err != nil {
                    http.Error(w, "action in unknown state, check state before attempting again", http.StatusInternalServerError)
                    return
                }
                w.WriteHeader(http.StatusOK)
                return
            }
        }
        

        Index ▾

        Variables
        func Drivers() []string
        func Register(name string, driver driver.Driver)
        type ColumnType
            func (ci *ColumnType) DatabaseTypeName() string
            func (ci *ColumnType) DecimalSize() (precision, scale int64, ok bool)
            func (ci *ColumnType) Length() (length int64, ok bool)
            func (ci *ColumnType) Name() string
            func (ci *ColumnType) Nullable() (nullable, ok bool)
            func (ci *ColumnType) ScanType() reflect.Type
        type Conn
            func (c *Conn) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)
            func (c *Conn) Close() error
            func (c *Conn) ExecContext(ctx context.Context, query string, args ...any) (Result, error)
            func (c *Conn) PingContext(ctx context.Context) error
            func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error)
            func (c *Conn) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)
            func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...any) *Row
            func (c *Conn) Raw(f func(driverConn any) error) (err error)
        type DB
            func Open(driverName, dataSourceName string) (*DB, error)
            func OpenDB(c driver.Connector) *DB
            func (db *DB) Begin() (*Tx, error)
            func (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)
            func (db *DB) Close() error
            func (db *DB) Conn(ctx context.Context) (*Conn, error)
            func (db *DB) Driver() driver.Driver
            func (db *DB) Exec(query string, args ...any) (Result, error)
            func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (Result, error)
            func (db *DB) Ping() error
            func (db *DB) PingContext(ctx context.Context) error
            func (db *DB) Prepare(query string) (*Stmt, error)
            func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error)
            func (db *DB) Query(query string, args ...any) (*Rows, error)
            func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)
            func (db *DB) QueryRow(query string, args ...any) *Row
            func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *Row
            func (db *DB) SetConnMaxIdleTime(d time.Duration)
            func (db *DB) SetConnMaxLifetime(d time.Duration)
            func (db *DB) SetMaxIdleConns(n int)
            func (db *DB) SetMaxOpenConns(n int)
            func (db *DB) Stats() DBStats
        type DBStats
        type IsolationLevel
            func (i IsolationLevel) String() string
        type NamedArg
            func Named(name string, value any) NamedArg
        type Null
            func (n *Null[T]) Scan(value any) error
            func (n Null[T]) Value() (driver.Value, error)
        type NullBool
            func (n *NullBool) Scan(value any) error
            func (n NullBool) Value() (driver.Value, error)
        type NullByte
            func (n *NullByte) Scan(value any) error
            func (n NullByte) Value() (driver.Value, error)
        type NullFloat64
            func (n *NullFloat64) Scan(value any) error
            func (n NullFloat64) Value() (driver.Value, error)
        type NullInt16
            func (n *NullInt16) Scan(value any) error
            func (n NullInt16) Value() (driver.Value, error)
        type NullInt32
            func (n *NullInt32) Scan(value any) error
            func (n NullInt32) Value() (driver.Value, error)
        type NullInt64
            func (n *NullInt64) Scan(value any) error
            func (n NullInt64) Value() (driver.Value, error)
        type NullString
            func (ns *NullString) Scan(value any) error
            func (ns NullString) Value() (driver.Value, error)
        type NullTime
            func (n *NullTime) Scan(value any) error
            func (n NullTime) Value() (driver.Value, error)
        type Out
        type RawBytes
        type Result
        type Row
            func (r *Row) Err() error
            func (r *Row) Scan(dest ...any) error
        type Rows
            func (rs *Rows) Close() error
            func (rs *Rows) ColumnTypes() ([]*ColumnType, error)
            func (rs *Rows) Columns() ([]string, error)
            func (rs *Rows) Err() error
            func (rs *Rows) Next() bool
            func (rs *Rows) NextResultSet() bool
            func (rs *Rows) Scan(dest ...any) error
        type Scanner
        type Stmt
            func (s *Stmt) Close() error
            func (s *Stmt) Exec(args ...any) (Result, error)
            func (s *Stmt) ExecContext(ctx context.Context, args ...any) (Result, error)
            func (s *Stmt) Query(args ...any) (*Rows, error)
            func (s *Stmt) QueryContext(ctx context.Context, args ...any) (*Rows, error)
            func (s *Stmt) QueryRow(args ...any) *Row
            func (s *Stmt) QueryRowContext(ctx context.Context, args ...any) *Row
        type Tx
            func (tx *Tx) Commit() error
            func (tx *Tx) Exec(query string, args ...any) (Result, error)
            func (tx *Tx) ExecContext(ctx context.Context, query string, args ...any) (Result, error)
            func (tx *Tx) Prepare(query string) (*Stmt, error)
            func (tx *Tx) PrepareContext(ctx context.Context, query string) (*Stmt, error)
            func (tx *Tx) Query(query string, args ...any) (*Rows, error)
            func (tx *Tx) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)
            func (tx *Tx) QueryRow(query string, args ...any) *Row
            func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *Row
            func (tx *Tx) Rollback() error
            func (tx *Tx) Stmt(stmt *Stmt) *Stmt
            func (tx *Tx) StmtContext(ctx context.Context, stmt *Stmt) *Stmt
        type TxOptions

        Package files

        convert.go ctxutil.go sql.go

        Variables

        ErrConnDone is returned by any operation that is performed on a connection that has already been returned to the connection pool.

        var ErrConnDone = errors.New("sql: connection is already closed")

        ErrNoRows is returned by Row.Scan when DB.QueryRow doesn't return a row. In such a case, QueryRow returns a placeholder *Row value that defers this error until a Scan.

        var ErrNoRows = errors.New("sql: no rows in result set")

        ErrTxDone is returned by any operation that is performed on a transaction that has already been committed or rolled back.

        var ErrTxDone = errors.New("sql: transaction has already been committed or rolled back")

        func Drivers

        func Drivers() []string

        Drivers returns a sorted list of the names of the registered drivers.

        func Register

        func Register(name string, driver driver.Driver)

        Register makes a database driver available by the provided name. If Register is called twice with the same name or if driver is nil, it panics.

        type ColumnType

        ColumnType contains the name and type of a column.

        type ColumnType struct {
            // contains filtered or unexported fields
        }
        

        func (*ColumnType) DatabaseTypeName

        func (ci *ColumnType) DatabaseTypeName() string

        DatabaseTypeName returns the database system name of the column type. If an empty string is returned, then the driver type name is not supported. Consult your driver documentation for a list of driver data types. ColumnType.Length specifiers are not included. Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", "INT", and "BIGINT".

        func (*ColumnType) DecimalSize

        func (ci *ColumnType) DecimalSize() (precision, scale int64, ok bool)

        DecimalSize returns the scale and precision of a decimal type. If not applicable or if not supported ok is false.

        func (*ColumnType) Length

        func (ci *ColumnType) Length() (length int64, ok bool)

        Length returns the column type length for variable length column types such as text and binary field types. If the type length is unbounded the value will be math.MaxInt64 (any database limits will still apply). If the column type is not variable length, such as an int, or if not supported by the driver ok is false.

        func (*ColumnType) Name

        func (ci *ColumnType) Name() string

        Name returns the name or alias of the column.

        func (*ColumnType) Nullable

        func (ci *ColumnType) Nullable() (nullable, ok bool)

        Nullable reports whether the column may be null. If a driver does not support this property ok will be false.

        func (*ColumnType) ScanType

        func (ci *ColumnType) ScanType() reflect.Type

        ScanType returns a Go type suitable for scanning into using Rows.Scan. If a driver does not support this property ScanType will return the type of an empty interface.

        type Conn

        Conn represents a single database connection rather than a pool of database connections. Prefer running queries from DB unless there is a specific need for a continuous single database connection.

        A Conn must call Conn.Close to return the connection to the database pool and may do so concurrently with a running query.

        After a call to Conn.Close, all operations on the connection fail with ErrConnDone.

        type Conn struct {
            // contains filtered or unexported fields
        }
        

        func (*Conn) BeginTx

        func (c *Conn) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)

        BeginTx starts a transaction.

        The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled.

        The provided TxOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.

        func (*Conn) Close

        func (c *Conn) Close() error

        Close returns the connection to the connection pool. All operations after a Close will return with ErrConnDone. Close is safe to call concurrently with other operations and will block until all other operations finish. It may be useful to first cancel any used context and then call close directly after.

        func (*Conn) ExecContext

        func (c *Conn) ExecContext(ctx context.Context, query string, args ...any) (Result, error)

        ExecContext executes a query without returning any rows. The args are for any placeholder parameters in the query.

        Example

        Code:

        // A *DB is a pool of connections. Call Conn to reserve a connection for
        // exclusive use.
        conn, err := db.Conn(ctx)
        if err != nil {
            log.Fatal(err)
        }
        defer conn.Close() // Return the connection to the pool.
        id := 41
        result, err := conn.ExecContext(ctx, `UPDATE balances SET balance = balance + 10 WHERE user_id = ?;`, id)
        if err != nil {
            log.Fatal(err)
        }
        rows, err := result.RowsAffected()
        if err != nil {
            log.Fatal(err)
        }
        if rows != 1 {
            log.Fatalf("expected single row affected, got %d rows affected", rows)
        }
        

        func (*Conn) PingContext

        func (c *Conn) PingContext(ctx context.Context) error

        PingContext verifies the connection to the database is still alive.

        func (*Conn) PrepareContext

        func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error)

        PrepareContext creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's *Stmt.Close method when the statement is no longer needed.

        The provided context is used for the preparation of the statement, not for the execution of the statement.

        func (*Conn) QueryContext

        func (c *Conn) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)

        QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

        func (*Conn) QueryRowContext

        func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...any) *Row

        QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until the *Row.Scan method is called. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row and discards the rest.

        func (*Conn) Raw

        func (c *Conn) Raw(f func(driverConn any) error) (err error)

        Raw executes f exposing the underlying driver connection for the duration of f. The driverConn must not be used outside of f.

        Once f returns and err is not driver.ErrBadConn, the Conn will continue to be usable until Conn.Close is called.

        type DB

        DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines.

        The sql package creates and frees connections automatically; it also maintains a free pool of idle connections. If the database has a concept of per-connection state, such state can be reliably observed within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the returned Tx is bound to a single connection. Once Tx.Commit or Tx.Rollback is called on the transaction, that transaction's connection is returned to DB's idle connection pool. The pool size can be controlled with DB.SetMaxIdleConns.

        type DB struct {
            // contains filtered or unexported fields
        }
        

        func Open

        func Open(driverName, dataSourceName string) (*DB, error)

        Open opens a database specified by its database driver name and a driver-specific data source name, usually consisting of at least a database name and connection information.

        Most users will open a database via a driver-specific connection helper function that returns a *DB. No database drivers are included in the Go standard library. See https://golang.org/s/sqldrivers for a list of third-party drivers.

        Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call DB.Ping.

        The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

        func OpenDB

        func OpenDB(c driver.Connector) *DB

        OpenDB opens a database using a driver.Connector, allowing drivers to bypass a string based data source name.

        Most users will open a database via a driver-specific connection helper function that returns a *DB. No database drivers are included in the Go standard library. See https://golang.org/s/sqldrivers for a list of third-party drivers.

        OpenDB may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call DB.Ping.

        The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the OpenDB function should be called just once. It is rarely necessary to close a DB.

        func (*DB) Begin

        func (db *DB) Begin() (*Tx, error)

        Begin starts a transaction. The default isolation level is dependent on the driver.

        Begin uses context.Background internally; to specify the context, use DB.BeginTx.

        func (*DB) BeginTx

        func (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)

        BeginTx starts a transaction.

        The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled.

        The provided TxOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.

        Example

        Code:

        tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
        if err != nil {
            log.Fatal(err)
        }
        id := 37
        _, execErr := tx.Exec(`UPDATE users SET status = ? WHERE id = ?`, "paid", id)
        if execErr != nil {
            _ = tx.Rollback()
            log.Fatal(execErr)
        }
        if err := tx.Commit(); err != nil {
            log.Fatal(err)
        }
        

        func (*DB) Close

        func (db *DB) Close() error

        Close closes the database and prevents new queries from starting. Close then waits for all queries that have started processing on the server to finish.

        It is rare to Close a DB, as the DB handle is meant to be long-lived and shared between many goroutines.

        func (*DB) Conn

        func (db *DB) Conn(ctx context.Context) (*Conn, error)

        Conn returns a single connection by either opening a new connection or returning an existing connection from the connection pool. Conn will block until either a connection is returned or ctx is canceled. Queries run on the same Conn will be run in the same database session.

        Every Conn must be returned to the database pool after use by calling Conn.Close.

        func (*DB) Driver

        func (db *DB) Driver() driver.Driver

        Driver returns the database's underlying driver.

        func (*DB) Exec

        func (db *DB) Exec(query string, args ...any) (Result, error)

        Exec executes a query without returning any rows. The args are for any placeholder parameters in the query.

        Exec uses context.Background internally; to specify the context, use DB.ExecContext.

        func (*DB) ExecContext

        func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (Result, error)

        ExecContext executes a query without returning any rows. The args are for any placeholder parameters in the query.

        Example

        Code:

        id := 47
        result, err := db.ExecContext(ctx, "UPDATE balances SET balance = balance + 10 WHERE user_id = ?", id)
        if err != nil {
            log.Fatal(err)
        }
        rows, err := result.RowsAffected()
        if err != nil {
            log.Fatal(err)
        }
        if rows != 1 {
            log.Fatalf("expected to affect 1 row, affected %d", rows)
        }
        

        func (*DB) Ping

        func (db *DB) Ping() error

        Ping verifies a connection to the database is still alive, establishing a connection if necessary.

        Ping uses context.Background internally; to specify the context, use DB.PingContext.

        func (*DB) PingContext

        func (db *DB) PingContext(ctx context.Context) error

        PingContext verifies a connection to the database is still alive, establishing a connection if necessary.

        Example

        Code:

        // Ping and PingContext may be used to determine if communication with
        // the database server is still possible.
        //
        // When used in a command line application Ping may be used to establish
        // that further queries are possible; that the provided DSN is valid.
        //
        // When used in long running service Ping may be part of the health
        // checking system.
        
        ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
        defer cancel()
        
        status := "up"
        if err := db.PingContext(ctx); err != nil {
            status = "down"
        }
        log.Println(status)
        

        func (*DB) Prepare

        func (db *DB) Prepare(query string) (*Stmt, error)

        Prepare creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's *Stmt.Close method when the statement is no longer needed.

        Prepare uses context.Background internally; to specify the context, use DB.PrepareContext.

        Example

        Code:

        projects := []struct {
            mascot  string
            release int
        }{
            {"tux", 1991},
            {"duke", 1996},
            {"gopher", 2009},
            {"moby dock", 2013},
        }
        
        stmt, err := db.Prepare("INSERT INTO projects(id, mascot, release, category) VALUES( ?, ?, ?, ? )")
        if err != nil {
            log.Fatal(err)
        }
        defer stmt.Close() // Prepared statements take up server resources and should be closed after use.
        
        for id, project := range projects {
            if _, err := stmt.Exec(id+1, project.mascot, project.release, "open source"); err != nil {
                log.Fatal(err)
            }
        }
        

        func (*DB) PrepareContext

        func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error)

        PrepareContext creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's *Stmt.Close method when the statement is no longer needed.

        The provided context is used for the preparation of the statement, not for the execution of the statement.

        func (*DB) Query

        func (db *DB) Query(query string, args ...any) (*Rows, error)

        Query executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

        Query uses context.Background internally; to specify the context, use DB.QueryContext.

        Example (MultipleResultSets)

        Code:

        age := 27
        q := `
        create temp table uid (id bigint); -- Create temp table for queries.
        insert into uid
        select id from users where age < ?; -- Populate temp table.
        
        -- First result set.
        select
            users.id, name
        from
            users
            join uid on users.id = uid.id
        ;
        
        -- Second result set.
        select 
            ur.user, ur.role
        from
            user_roles as ur
            join uid on uid.id = ur.user
        ;
            `
        rows, err := db.Query(q, age)
        if err != nil {
            log.Fatal(err)
        }
        defer rows.Close()
        
        for rows.Next() {
            var (
                id   int64
                name string
            )
            if err := rows.Scan(&id, &name); err != nil {
                log.Fatal(err)
            }
            log.Printf("id %d name is %s\n", id, name)
        }
        if !rows.NextResultSet() {
            log.Fatalf("expected more result sets: %v", rows.Err())
        }
        var roleMap = map[int64]string{
            1: "user",
            2: "admin",
            3: "gopher",
        }
        for rows.Next() {
            var (
                id   int64
                role int64
            )
            if err := rows.Scan(&id, &role); err != nil {
                log.Fatal(err)
            }
            log.Printf("id %d has role %s\n", id, roleMap[role])
        }
        if err := rows.Err(); err != nil {
            log.Fatal(err)
        }
        

        func (*DB) QueryContext

        func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)

        QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

        Example

        Code:

        age := 27
        rows, err := db.QueryContext(ctx, "SELECT name FROM users WHERE age=?", age)
        if err != nil {
            log.Fatal(err)
        }
        defer rows.Close()
        names := make([]string, 0)
        
        for rows.Next() {
            var name string
            if err := rows.Scan(&name); err != nil {
                // Check for a scan error.
                // Query rows will be closed with defer.
                log.Fatal(err)
            }
            names = append(names, name)
        }
        // If the database is being written to ensure to check for Close
        // errors that may be returned from the driver. The query may
        // encounter an auto-commit error and be forced to rollback changes.
        rerr := rows.Close()
        if rerr != nil {
            log.Fatal(rerr)
        }
        
        // Rows.Err will report the last error encountered by Rows.Scan.
        if err := rows.Err(); err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s are %d years old", strings.Join(names, ", "), age)
        

        func (*DB) QueryRow

        func (db *DB) QueryRow(query string, args ...any) *Row

        QueryRow executes a query that is expected to return at most one row. QueryRow always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, *Row.Scan scans the first selected row and discards the rest.

        QueryRow uses context.Background internally; to specify the context, use DB.QueryRowContext.

        func (*DB) QueryRowContext

        func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *Row

        QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, *Row.Scan scans the first selected row and discards the rest.

        Example

        Code:

        id := 123
        var username string
        var created time.Time
        err := db.QueryRowContext(ctx, "SELECT username, created_at FROM users WHERE id=?", id).Scan(&username, &created)
        switch {
        case err == sql.ErrNoRows:
            log.Printf("no user with id %d\n", id)
        case err != nil:
            log.Fatalf("query error: %v\n", err)
        default:
            log.Printf("username is %q, account created on %s\n", username, created)
        }
        

        func (*DB) SetConnMaxIdleTime

        func (db *DB) SetConnMaxIdleTime(d time.Duration)

        SetConnMaxIdleTime sets the maximum amount of time a connection may be idle.

        Expired connections may be closed lazily before reuse.

        If d <= 0, connections are not closed due to a connection's idle time.

        func (*DB) SetConnMaxLifetime

        func (db *DB) SetConnMaxLifetime(d time.Duration)

        SetConnMaxLifetime sets the maximum amount of time a connection may be reused.

        Expired connections may be closed lazily before reuse.

        If d <= 0, connections are not closed due to a connection's age.

        func (*DB) SetMaxIdleConns

        func (db *DB) SetMaxIdleConns(n int)

        SetMaxIdleConns sets the maximum number of connections in the idle connection pool.

        If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, then the new MaxIdleConns will be reduced to match the MaxOpenConns limit.

        If n <= 0, no idle connections are retained.

        The default max idle connections is currently 2. This may change in a future release.

        func (*DB) SetMaxOpenConns

        func (db *DB) SetMaxOpenConns(n int)

        SetMaxOpenConns sets the maximum number of open connections to the database.

        If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than MaxIdleConns, then MaxIdleConns will be reduced to match the new MaxOpenConns limit.

        If n <= 0, then there is no limit on the number of open connections. The default is 0 (unlimited).

        func (*DB) Stats

        func (db *DB) Stats() DBStats

        Stats returns database statistics.

        type DBStats

        DBStats contains database statistics.

        type DBStats struct {
            MaxOpenConnections int // Maximum number of open connections to the database.
        
            // Pool Status
            OpenConnections int // The number of established connections both in use and idle.
            InUse           int // The number of connections currently in use.
            Idle            int // The number of idle connections.
        
            // Counters
            WaitCount         int64         // The total number of connections waited for.
            WaitDuration      time.Duration // The total time blocked waiting for a new connection.
            MaxIdleClosed     int64         // The total number of connections closed due to SetMaxIdleConns.
            MaxIdleTimeClosed int64         // The total number of connections closed due to SetConnMaxIdleTime.
            MaxLifetimeClosed int64         // The total number of connections closed due to SetConnMaxLifetime.
        }
        

        type IsolationLevel

        IsolationLevel is the transaction isolation level used in TxOptions.

        type IsolationLevel int

        Various isolation levels that drivers may support in DB.BeginTx. If a driver does not support a given isolation level an error may be returned.

        See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.

        const (
            LevelDefault IsolationLevel = iota
            LevelReadUncommitted
            LevelReadCommitted
            LevelWriteCommitted
            LevelRepeatableRead
            LevelSnapshot
            LevelSerializable
            LevelLinearizable
        )

        func (IsolationLevel) String

        func (i IsolationLevel) String() string

        String returns the name of the transaction isolation level.

        type NamedArg

        A NamedArg is a named argument. NamedArg values may be used as arguments to DB.Query or DB.Exec and bind to the corresponding named parameter in the SQL statement.

        For a more concise way to create NamedArg values, see the Named function.

        type NamedArg struct {
        
            // Name is the name of the parameter placeholder.
            //
            // If empty, the ordinal position in the argument list will be
            // used.
            //
            // Name must omit any symbol prefix.
            Name string
        
            // Value is the value of the parameter.
            // It may be assigned the same value types as the query
            // arguments.
            Value any
            // contains filtered or unexported fields
        }
        

        func Named

        func Named(name string, value any) NamedArg

        Named provides a more concise way to create NamedArg values.

        Example usage:

        db.ExecContext(ctx, `
            delete from Invoice
            where
                TimeCreated < @end
                and TimeCreated >= @start;`,
            sql.Named("start", startTime),
            sql.Named("end", endTime),
        )
        

        type Null

        Null represents a value that may be null. Null implements the Scanner interface so it can be used as a scan destination:

        var s Null[string]
        err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
        ...
        if s.Valid {
           // use s.V
        } else {
           // NULL value
        }
        
        type Null[T any] struct {
            V     T
            Valid bool
        }
        

        func (*Null[T]) Scan

        func (n *Null[T]) Scan(value any) error

        func (Null[T]) Value

        func (n Null[T]) Value() (driver.Value, error)

        type NullBool

        NullBool represents a bool that may be null. NullBool implements the Scanner interface so it can be used as a scan destination, similar to NullString.

        type NullBool struct {
            Bool  bool
            Valid bool // Valid is true if Bool is not NULL
        }
        

        func (*NullBool) Scan

        func (n *NullBool) Scan(value any) error

        Scan implements the Scanner interface.

        func (NullBool) Value

        func (n NullBool) Value() (driver.Value, error)

        Value implements the driver.Valuer interface.

        type NullByte

        NullByte represents a byte that may be null. NullByte implements the Scanner interface so it can be used as a scan destination, similar to NullString.

        type NullByte struct {
            Byte  byte
            Valid bool // Valid is true if Byte is not NULL
        }
        

        func (*NullByte) Scan

        func (n *NullByte) Scan(value any) error

        Scan implements the Scanner interface.

        func (NullByte) Value

        func (n NullByte) Value() (driver.Value, error)

        Value implements the driver.Valuer interface.

        type NullFloat64

        NullFloat64 represents a float64 that may be null. NullFloat64 implements the Scanner interface so it can be used as a scan destination, similar to NullString.

        type NullFloat64 struct {
            Float64 float64
            Valid   bool // Valid is true if Float64 is not NULL
        }
        

        func (*NullFloat64) Scan

        func (n *NullFloat64) Scan(value any) error

        Scan implements the Scanner interface.

        func (NullFloat64) Value

        func (n NullFloat64) Value() (driver.Value, error)

        Value implements the driver.Valuer interface.

        type NullInt16

        NullInt16 represents an int16 that may be null. NullInt16 implements the Scanner interface so it can be used as a scan destination, similar to NullString.

        type NullInt16 struct {
            Int16 int16
            Valid bool // Valid is true if Int16 is not NULL
        }
        

        func (*NullInt16) Scan

        func (n *NullInt16) Scan(value any) error

        Scan implements the Scanner interface.

        func (NullInt16) Value

        func (n NullInt16) Value() (driver.Value, error)

        Value implements the driver.Valuer interface.

        type NullInt32

        NullInt32 represents an int32 that may be null. NullInt32 implements the Scanner interface so it can be used as a scan destination, similar to NullString.

        type NullInt32 struct {
            Int32 int32
            Valid bool // Valid is true if Int32 is not NULL
        }
        

        func (*NullInt32) Scan

        func (n *NullInt32) Scan(value any) error

        Scan implements the Scanner interface.

        func (NullInt32) Value

        func (n NullInt32) Value() (driver.Value, error)

        Value implements the driver.Valuer interface.

        type NullInt64

        NullInt64 represents an int64 that may be null. NullInt64 implements the Scanner interface so it can be used as a scan destination, similar to NullString.

        type NullInt64 struct {
            Int64 int64
            Valid bool // Valid is true if Int64 is not NULL
        }
        

        func (*NullInt64) Scan

        func (n *NullInt64) Scan(value any) error

        Scan implements the Scanner interface.

        func (NullInt64) Value

        func (n NullInt64) Value() (driver.Value, error)

        Value implements the driver.Valuer interface.

        type NullString

        NullString represents a string that may be null. NullString implements the Scanner interface so it can be used as a scan destination:

        var s NullString
        err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
        ...
        if s.Valid {
           // use s.String
        } else {
           // NULL value
        }
        
        type NullString struct {
            String string
            Valid  bool // Valid is true if String is not NULL
        }
        

        func (*NullString) Scan

        func (ns *NullString) Scan(value any) error

        Scan implements the Scanner interface.

        func (NullString) Value

        func (ns NullString) Value() (driver.Value, error)

        Value implements the driver.Valuer interface.

        type NullTime

        NullTime represents a time.Time that may be null. NullTime implements the Scanner interface so it can be used as a scan destination, similar to NullString.

        type NullTime struct {
            Time  time.Time
            Valid bool // Valid is true if Time is not NULL
        }
        

        func (*NullTime) Scan

        func (n *NullTime) Scan(value any) error

        Scan implements the Scanner interface.

        func (NullTime) Value

        func (n NullTime) Value() (driver.Value, error)

        Value implements the driver.Valuer interface.

        type Out

        Out may be used to retrieve OUTPUT value parameters from stored procedures.

        Not all drivers and databases support OUTPUT value parameters.

        Example usage:

        var outArg string
        _, err := db.ExecContext(ctx, "ProcName", sql.Named("Arg1", sql.Out{Dest: &outArg}))
        
        type Out struct {
        
            // Dest is a pointer to the value that will be set to the result of the
            // stored procedure's OUTPUT parameter.
            Dest any
        
            // In is whether the parameter is an INOUT parameter. If so, the input value to the stored
            // procedure is the dereferenced value of Dest's pointer, which is then replaced with
            // the output value.
            In bool
            // contains filtered or unexported fields
        }
        

        type RawBytes

        RawBytes is a byte slice that holds a reference to memory owned by the database itself. After a Rows.Scan into a RawBytes, the slice is only valid until the next call to Rows.Next, Rows.Scan, or Rows.Close.

        type RawBytes []byte

        type Result

        A Result summarizes an executed SQL command.

        type Result interface {
            // LastInsertId returns the integer generated by the database
            // in response to a command. Typically this will be from an
            // "auto increment" column when inserting a new row. Not all
            // databases support this feature, and the syntax of such
            // statements varies.
            LastInsertId() (int64, error)
        
            // RowsAffected returns the number of rows affected by an
            // update, insert, or delete. Not every database or database
            // driver may support this.
            RowsAffected() (int64, error)
        }

        type Row

        Row is the result of calling DB.QueryRow to select a single row.

        type Row struct {
            // contains filtered or unexported fields
        }
        

        func (*Row) Err

        func (r *Row) Err() error

        Err provides a way for wrapping packages to check for query errors without calling Row.Scan. Err returns the error, if any, that was encountered while running the query. If this error is not nil, this error will also be returned from Row.Scan.

        func (*Row) Scan

        func (r *Row) Scan(dest ...any) error

        Scan copies the columns from the matched row into the values pointed at by dest. See the documentation on Rows.Scan for details. If more than one row matches the query, Scan uses the first row and discards the rest. If no row matches the query, Scan returns ErrNoRows.

        type Rows

        Rows is the result of a query. Its cursor starts before the first row of the result set. Use Rows.Next to advance from row to row.

        type Rows struct {
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        age := 27
        rows, err := db.QueryContext(ctx, "SELECT name FROM users WHERE age=?", age)
        if err != nil {
            log.Fatal(err)
        }
        defer rows.Close()
        
        names := make([]string, 0)
        for rows.Next() {
            var name string
            if err := rows.Scan(&name); err != nil {
                log.Fatal(err)
            }
            names = append(names, name)
        }
        // Check for errors from iterating over rows.
        if err := rows.Err(); err != nil {
            log.Fatal(err)
        }
        log.Printf("%s are %d years old", strings.Join(names, ", "), age)
        

        func (*Rows) Close

        func (rs *Rows) Close() error

        Close closes the Rows, preventing further enumeration. If Rows.Next is called and returns false and there are no further result sets, the Rows are closed automatically and it will suffice to check the result of Rows.Err. Close is idempotent and does not affect the result of Rows.Err.

        func (*Rows) ColumnTypes

        func (rs *Rows) ColumnTypes() ([]*ColumnType, error)

        ColumnTypes returns column information such as column type, length, and nullable. Some information may not be available from some drivers.

        func (*Rows) Columns

        func (rs *Rows) Columns() ([]string, error)

        Columns returns the column names. Columns returns an error if the rows are closed.

        func (*Rows) Err

        func (rs *Rows) Err() error

        Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Rows.Close.

        func (*Rows) Next

        func (rs *Rows) Next() bool

        Next prepares the next result row for reading with the Rows.Scan method. It returns true on success, or false if there is no next result row or an error happened while preparing it. Rows.Err should be consulted to distinguish between the two cases.

        Every call to Rows.Scan, even the first one, must be preceded by a call to Rows.Next.

        func (*Rows) NextResultSet

        func (rs *Rows) NextResultSet() bool

        NextResultSet prepares the next result set for reading. It reports whether there is further result sets, or false if there is no further result set or if there is an error advancing to it. The Rows.Err method should be consulted to distinguish between the two cases.

        After calling NextResultSet, the Rows.Next method should always be called before scanning. If there are further result sets they may not have rows in the result set.

        func (*Rows) Scan

        func (rs *Rows) Scan(dest ...any) error

        Scan copies the columns in the current row into the values pointed at by dest. The number of values in dest must be the same as the number of columns in Rows.

        Scan converts columns read from the database into the following common Go types and special types provided by the sql package:

        *string
        *[]byte
        *int, *int8, *int16, *int32, *int64
        *uint, *uint8, *uint16, *uint32, *uint64
        *bool
        *float32, *float64
        *interface{}
        *RawBytes
        *Rows (cursor value)
        any type implementing Scanner (see Scanner docs)
        

        In the most simple case, if the type of the value from the source column is an integer, bool or string type T and dest is of type *T, Scan simply assigns the value through the pointer.

        Scan also converts between string and numeric types, as long as no information would be lost. While Scan stringifies all numbers scanned from numeric database columns into *string, scans into numeric types are checked for overflow. For example, a float64 with value 300 or a string with value "300" can scan into a uint16, but not into a uint8, though float64(255) or "255" can scan into a uint8. One exception is that scans of some float64 numbers to strings may lose information when stringifying. In general, scan floating point columns into *float64.

        If a dest argument has type *[]byte, Scan saves in that argument a copy of the corresponding data. The copy is owned by the caller and can be modified and held indefinitely. The copy can be avoided by using an argument of type *RawBytes instead; see the documentation for RawBytes for restrictions on its use.

        If an argument has type *interface{}, Scan copies the value provided by the underlying driver without conversion. When scanning from a source value of type []byte to *interface{}, a copy of the slice is made and the caller owns the result.

        Source values of type time.Time may be scanned into values of type *time.Time, *interface{}, *string, or *[]byte. When converting to the latter two, time.RFC3339Nano is used.

        Source values of type bool may be scanned into types *bool, *interface{}, *string, *[]byte, or *RawBytes.

        For scanning into *bool, the source may be true, false, 1, 0, or string inputs parseable by strconv.ParseBool.

        Scan can also convert a cursor returned from a query, such as "select cursor(select * from my_table) from dual", into a *Rows value that can itself be scanned from. The parent select query will close any cursor *Rows if the parent *Rows is closed.

        If any of the first arguments implementing Scanner returns an error, that error will be wrapped in the returned error.

        type Scanner

        Scanner is an interface used by Rows.Scan.

        type Scanner interface {
            // Scan assigns a value from a database driver.
            //
            // The src value will be of one of the following types:
            //
            //    int64
            //    float64
            //    bool
            //    []byte
            //    string
            //    time.Time
            //    nil - for NULL values
            //
            // An error should be returned if the value cannot be stored
            // without loss of information.
            //
            // Reference types such as []byte are only valid until the next call to Scan
            // and should not be retained. Their underlying memory is owned by the driver.
            // If retention is necessary, copy their values before the next call to Scan.
            Scan(src any) error
        }

        type Stmt

        Stmt is a prepared statement. A Stmt is safe for concurrent use by multiple goroutines.

        If a Stmt is prepared on a Tx or Conn, it will be bound to a single underlying connection forever. If the Tx or Conn closes, the Stmt will become unusable and all operations will return an error. If a Stmt is prepared on a DB, it will remain usable for the lifetime of the DB. When the Stmt needs to execute on a new underlying connection, it will prepare itself on the new connection automatically.

        type Stmt struct {
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        // In normal use, create one Stmt when your process starts.
        stmt, err := db.PrepareContext(ctx, "SELECT username FROM users WHERE id = ?")
        if err != nil {
            log.Fatal(err)
        }
        defer stmt.Close()
        
        // Then reuse it each time you need to issue the query.
        id := 43
        var username string
        err = stmt.QueryRowContext(ctx, id).Scan(&username)
        switch {
        case err == sql.ErrNoRows:
            log.Fatalf("no user with id %d", id)
        case err != nil:
            log.Fatal(err)
        default:
            log.Printf("username is %s\n", username)
        }
        

        func (*Stmt) Close

        func (s *Stmt) Close() error

        Close closes the statement.

        func (*Stmt) Exec

        func (s *Stmt) Exec(args ...any) (Result, error)

        Exec executes a prepared statement with the given arguments and returns a Result summarizing the effect of the statement.

        Exec uses context.Background internally; to specify the context, use Stmt.ExecContext.

        func (*Stmt) ExecContext

        func (s *Stmt) ExecContext(ctx context.Context, args ...any) (Result, error)

        ExecContext executes a prepared statement with the given arguments and returns a Result summarizing the effect of the statement.

        func (*Stmt) Query

        func (s *Stmt) Query(args ...any) (*Rows, error)

        Query executes a prepared query statement with the given arguments and returns the query results as a *Rows.

        Query uses context.Background internally; to specify the context, use Stmt.QueryContext.

        func (*Stmt) QueryContext

        func (s *Stmt) QueryContext(ctx context.Context, args ...any) (*Rows, error)

        QueryContext executes a prepared query statement with the given arguments and returns the query results as a *Rows.

        func (*Stmt) QueryRow

        func (s *Stmt) QueryRow(args ...any) *Row

        QueryRow executes a prepared query statement with the given arguments. If an error occurs during the execution of the statement, that error will be returned by a call to Scan on the returned *Row, which is always non-nil. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row and discards the rest.

        Example usage:

        var name string
        err := nameByUseridStmt.QueryRow(id).Scan(&name)
        

        QueryRow uses context.Background internally; to specify the context, use Stmt.QueryRowContext.

        func (*Stmt) QueryRowContext

        func (s *Stmt) QueryRowContext(ctx context.Context, args ...any) *Row

        QueryRowContext executes a prepared query statement with the given arguments. If an error occurs during the execution of the statement, that error will be returned by a call to Scan on the returned *Row, which is always non-nil. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row and discards the rest.

        Example

        Code:

        // In normal use, create one Stmt when your process starts.
        stmt, err := db.PrepareContext(ctx, "SELECT username FROM users WHERE id = ?")
        if err != nil {
            log.Fatal(err)
        }
        defer stmt.Close()
        
        // Then reuse it each time you need to issue the query.
        id := 43
        var username string
        err = stmt.QueryRowContext(ctx, id).Scan(&username)
        switch {
        case err == sql.ErrNoRows:
            log.Fatalf("no user with id %d", id)
        case err != nil:
            log.Fatal(err)
        default:
            log.Printf("username is %s\n", username)
        }
        

        type Tx

        Tx is an in-progress database transaction.

        A transaction must end with a call to Tx.Commit or Tx.Rollback.

        After a call to Tx.Commit or Tx.Rollback, all operations on the transaction fail with ErrTxDone.

        The statements prepared for a transaction by calling the transaction's Tx.Prepare or Tx.Stmt methods are closed by the call to Tx.Commit or Tx.Rollback.

        type Tx struct {
            // contains filtered or unexported fields
        }
        

        func (*Tx) Commit

        func (tx *Tx) Commit() error

        Commit commits the transaction.

        func (*Tx) Exec

        func (tx *Tx) Exec(query string, args ...any) (Result, error)

        Exec executes a query that doesn't return rows. For example: an INSERT and UPDATE.

        Exec uses context.Background internally; to specify the context, use Tx.ExecContext.

        func (*Tx) ExecContext

        func (tx *Tx) ExecContext(ctx context.Context, query string, args ...any) (Result, error)

        ExecContext executes a query that doesn't return rows. For example: an INSERT and UPDATE.

        Example

        Code:

        tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
        if err != nil {
            log.Fatal(err)
        }
        id := 37
        _, execErr := tx.ExecContext(ctx, "UPDATE users SET status = ? WHERE id = ?", "paid", id)
        if execErr != nil {
            if rollbackErr := tx.Rollback(); rollbackErr != nil {
                log.Fatalf("update failed: %v, unable to rollback: %v\n", execErr, rollbackErr)
            }
            log.Fatalf("update failed: %v", execErr)
        }
        if err := tx.Commit(); err != nil {
            log.Fatal(err)
        }
        

        func (*Tx) Prepare

        func (tx *Tx) Prepare(query string) (*Stmt, error)

        Prepare creates a prepared statement for use within a transaction.

        The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

        To use an existing prepared statement on this transaction, see Tx.Stmt.

        Prepare uses context.Background internally; to specify the context, use Tx.PrepareContext.

        Example

        Code:

        projects := []struct {
            mascot  string
            release int
        }{
            {"tux", 1991},
            {"duke", 1996},
            {"gopher", 2009},
            {"moby dock", 2013},
        }
        
        tx, err := db.Begin()
        if err != nil {
            log.Fatal(err)
        }
        defer tx.Rollback() // The rollback will be ignored if the tx has been committed later in the function.
        
        stmt, err := tx.Prepare("INSERT INTO projects(id, mascot, release, category) VALUES( ?, ?, ?, ? )")
        if err != nil {
            log.Fatal(err)
        }
        defer stmt.Close() // Prepared statements take up server resources and should be closed after use.
        
        for id, project := range projects {
            if _, err := stmt.Exec(id+1, project.mascot, project.release, "open source"); err != nil {
                log.Fatal(err)
            }
        }
        if err := tx.Commit(); err != nil {
            log.Fatal(err)
        }
        

        func (*Tx) PrepareContext

        func (tx *Tx) PrepareContext(ctx context.Context, query string) (*Stmt, error)

        PrepareContext creates a prepared statement for use within a transaction.

        The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

        To use an existing prepared statement on this transaction, see Tx.Stmt.

        The provided context will be used for the preparation of the context, not for the execution of the returned statement. The returned statement will run in the transaction context.

        func (*Tx) Query

        func (tx *Tx) Query(query string, args ...any) (*Rows, error)

        Query executes a query that returns rows, typically a SELECT.

        Query uses context.Background internally; to specify the context, use Tx.QueryContext.

        func (*Tx) QueryContext

        func (tx *Tx) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)

        QueryContext executes a query that returns rows, typically a SELECT.

        func (*Tx) QueryRow

        func (tx *Tx) QueryRow(query string, args ...any) *Row

        QueryRow executes a query that is expected to return at most one row. QueryRow always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row and discards the rest.

        QueryRow uses context.Background internally; to specify the context, use Tx.QueryRowContext.

        func (*Tx) QueryRowContext

        func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *Row

        QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row and discards the rest.

        func (*Tx) Rollback

        func (tx *Tx) Rollback() error

        Rollback aborts the transaction.

        Example

        Code:

        tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
        if err != nil {
            log.Fatal(err)
        }
        id := 53
        _, err = tx.ExecContext(ctx, "UPDATE drivers SET status = ? WHERE id = ?;", "assigned", id)
        if err != nil {
            if rollbackErr := tx.Rollback(); rollbackErr != nil {
                log.Fatalf("update drivers: unable to rollback: %v", rollbackErr)
            }
            log.Fatal(err)
        }
        _, err = tx.ExecContext(ctx, "UPDATE pickups SET driver_id = $1;", id)
        if err != nil {
            if rollbackErr := tx.Rollback(); rollbackErr != nil {
                log.Fatalf("update failed: %v, unable to back: %v", err, rollbackErr)
            }
            log.Fatal(err)
        }
        if err := tx.Commit(); err != nil {
            log.Fatal(err)
        }
        

        func (*Tx) Stmt

        func (tx *Tx) Stmt(stmt *Stmt) *Stmt

        Stmt returns a transaction-specific prepared statement from an existing statement.

        Example:

        updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
        ...
        tx, err := db.Begin()
        ...
        res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
        

        The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

        Stmt uses context.Background internally; to specify the context, use Tx.StmtContext.

        func (*Tx) StmtContext

        func (tx *Tx) StmtContext(ctx context.Context, stmt *Stmt) *Stmt

        StmtContext returns a transaction-specific prepared statement from an existing statement.

        Example:

        updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
        ...
        tx, err := db.Begin()
        ...
        res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203)
        

        The provided context is used for the preparation of the statement, not for the execution of the statement.

        The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

        type TxOptions

        TxOptions holds the transaction options to be used in DB.BeginTx.

        type TxOptions struct {
            // Isolation is the transaction isolation level.
            // If zero, the driver or database's default level is used.
            Isolation IsolationLevel
            ReadOnly  bool
        }
        

        Subdirectories

        Name Synopsis
        ..
        driver Package driver defines interfaces to be implemented by database drivers as used by package sql.
        driver - Go Documentation Server
        ...

        Package driver

        import "database/sql/driver"
        Overview
        Index

        Overview ▾

        Package driver defines interfaces to be implemented by database drivers as used by package sql.

        Most code should use the database/sql package.

        The driver interface has evolved over time. Drivers should implement Connector and DriverContext interfaces. The Connector.Connect and Driver.Open methods should never return ErrBadConn. ErrBadConn should only be returned from Validator, SessionResetter, or a query method if the connection is already in an invalid (e.g. closed) state.

        All Conn implementations should implement the following interfaces: Pinger, SessionResetter, and Validator.

        If named parameters or context are supported, the driver's Conn should implement: ExecerContext, QueryerContext, ConnPrepareContext, and ConnBeginTx.

        To support custom data types, implement NamedValueChecker. NamedValueChecker also allows queries to accept per-query options as a parameter by returning ErrRemoveArgument from CheckNamedValue.

        If multiple result sets are supported, Rows should implement RowsNextResultSet. If the driver knows how to describe the types present in the returned result it should implement the following interfaces: RowsColumnTypeScanType, RowsColumnTypeDatabaseTypeName, RowsColumnTypeLength, RowsColumnTypeNullable, and RowsColumnTypePrecisionScale. A given row value may also return a Rows type, which may represent a database cursor value.

        If a Conn implements Validator, then the IsValid method is called before returning the connection to the connection pool. If an entry in the connection pool implements SessionResetter, then ResetSession is called before reusing the connection for another query. If a connection is never returned to the connection pool but is immediately reused, then ResetSession is called prior to reuse but IsValid is not called.

        Variables

        Bool is a ValueConverter that converts input values to bool.

        The conversion rules are:

        • booleans are returned unchanged
        • for integer types, 1 is true 0 is false, other integers are an error
        • for strings and []byte, same rules as strconv.ParseBool
        • all other types are an error
        var Bool boolType

        DefaultParameterConverter is the default implementation of ValueConverter that's used when a Stmt doesn't implement ColumnConverter.

        DefaultParameterConverter returns its argument directly if IsValue(arg). Otherwise, if the argument implements Valuer, its Value method is used to return a Value. As a fallback, the provided argument's underlying type is used to convert it to a Value: underlying integer types are converted to int64, floats to float64, bool, string, and []byte to themselves. If the argument is a nil pointer, defaultConverter.ConvertValue returns a nil Value. If the argument is a non-nil pointer, it is dereferenced and defaultConverter.ConvertValue is called recursively. Other types are an error.

        var DefaultParameterConverter defaultConverter

        ErrBadConn should be returned by a driver to signal to the database/sql package that a driver.Conn is in a bad state (such as the server having earlier closed the connection) and the database/sql package should retry on a new connection.

        To prevent duplicate operations, ErrBadConn should NOT be returned if there's a possibility that the database server might have performed the operation. Even if the server sends back an error, you shouldn't return ErrBadConn.

        Errors will be checked using errors.Is. An error may wrap ErrBadConn or implement the Is(error) bool method.

        var ErrBadConn = errors.New("driver: bad connection")

        ErrRemoveArgument may be returned from NamedValueChecker to instruct the database/sql package to not pass the argument to the driver query interface. Return when accepting query specific options or structures that aren't SQL query arguments.

        var ErrRemoveArgument = errors.New("driver: remove argument from query")

        ErrSkip may be returned by some optional interfaces' methods to indicate at runtime that the fast path is unavailable and the sql package should continue as if the optional interface was not implemented. ErrSkip is only supported where explicitly documented.

        var ErrSkip = errors.New("driver: skip fast-path; continue as if unimplemented")

        Int32 is a ValueConverter that converts input values to int64, respecting the limits of an int32 value.

        var Int32 int32Type

        ResultNoRows is a pre-defined Result for drivers to return when a DDL command (such as a CREATE TABLE) succeeds. It returns an error for both LastInsertId and RowsAffected.

        var ResultNoRows noRows

        String is a ValueConverter that converts its input to a string. If the value is already a string or []byte, it's unchanged. If the value is of another type, conversion to string is done with fmt.Sprintf("%v", v).

        var String stringType

        func IsScanValue

        func IsScanValue(v any) bool

        IsScanValue is equivalent to IsValue. It exists for compatibility.

        func IsValue

        func IsValue(v any) bool

        IsValue reports whether v is a valid Value parameter type.

        type ColumnConverter

        ColumnConverter may be optionally implemented by Stmt if the statement is aware of its own columns' types and can convert from any type to a driver Value.

        Deprecated: Drivers should implement NamedValueChecker.

        type ColumnConverter interface {
            // ColumnConverter returns a ValueConverter for the provided
            // column index. If the type of a specific column isn't known
            // or shouldn't be handled specially, DefaultValueConverter
            // can be returned.
            ColumnConverter(idx int) ValueConverter
        }

        type Conn

        Conn is a connection to a database. It is not used concurrently by multiple goroutines.

        Conn is assumed to be stateful.

        type Conn interface {
            // Prepare returns a prepared statement, bound to this connection.
            Prepare(query string) (Stmt, error)
        
            // Close invalidates and potentially stops any current
            // prepared statements and transactions, marking this
            // connection as no longer in use.
            //
            // Because the sql package maintains a free pool of
            // connections and only calls Close when there's a surplus of
            // idle connections, it shouldn't be necessary for drivers to
            // do their own connection caching.
            //
            // Drivers must ensure all network calls made by Close
            // do not block indefinitely (e.g. apply a timeout).
            Close() error
        
            // Begin starts and returns a new transaction.
            //
            // Deprecated: Drivers should implement ConnBeginTx instead (or additionally).
            Begin() (Tx, error)
        }

        type ConnBeginTx

        ConnBeginTx enhances the Conn interface with context and TxOptions.

        type ConnBeginTx interface {
            // BeginTx starts and returns a new transaction.
            // If the context is canceled by the user the sql package will
            // call Tx.Rollback before discarding and closing the connection.
            //
            // This must check opts.Isolation to determine if there is a set
            // isolation level. If the driver does not support a non-default
            // level and one is set or if there is a non-default isolation level
            // that is not supported, an error must be returned.
            //
            // This must also check opts.ReadOnly to determine if the read-only
            // value is true to either set the read-only transaction property if supported
            // or return an error if it is not supported.
            BeginTx(ctx context.Context, opts TxOptions) (Tx, error)
        }

        type ConnPrepareContext

        ConnPrepareContext enhances the Conn interface with context.

        type ConnPrepareContext interface {
            // PrepareContext returns a prepared statement, bound to this connection.
            // context is for the preparation of the statement,
            // it must not store the context within the statement itself.
            PrepareContext(ctx context.Context, query string) (Stmt, error)
        }

        type Connector

        A Connector represents a driver in a fixed configuration and can create any number of equivalent Conns for use by multiple goroutines.

        A Connector can be passed to database/sql.OpenDB, to allow drivers to implement their own database/sql.DB constructors, or returned by DriverContext's OpenConnector method, to allow drivers access to context and to avoid repeated parsing of driver configuration.

        If a Connector implements io.Closer, the database/sql.DB.Close method will call the Close method and return error (if any).

        type Connector interface {
            // Connect returns a connection to the database.
            // Connect may return a cached connection (one previously
            // closed), but doing so is unnecessary; the sql package
            // maintains a pool of idle connections for efficient re-use.
            //
            // The provided context.Context is for dialing purposes only
            // (see net.DialContext) and should not be stored or used for
            // other purposes. A default timeout should still be used
            // when dialing as a connection pool may call Connect
            // asynchronously to any query.
            //
            // The returned connection is only used by one goroutine at a
            // time.
            Connect(context.Context) (Conn, error)
        
            // Driver returns the underlying Driver of the Connector,
            // mainly to maintain compatibility with the Driver method
            // on sql.DB.
            Driver() Driver
        }

        type Driver

        Driver is the interface that must be implemented by a database driver.

        Database drivers may implement DriverContext for access to contexts and to parse the name only once for a pool of connections, instead of once per connection.

        type Driver interface {
            // Open returns a new connection to the database.
            // The name is a string in a driver-specific format.
            //
            // Open may return a cached connection (one previously
            // closed), but doing so is unnecessary; the sql package
            // maintains a pool of idle connections for efficient re-use.
            //
            // The returned connection is only used by one goroutine at a
            // time.
            Open(name string) (Conn, error)
        }

        type DriverContext

        If a Driver implements DriverContext, then database/sql.DB will call OpenConnector to obtain a Connector and then invoke that Connector's Connect method to obtain each needed connection, instead of invoking the Driver's Open method for each connection. The two-step sequence allows drivers to parse the name just once and also provides access to per-Conn contexts.

        type DriverContext interface {
            // OpenConnector must parse the name in the same format that Driver.Open
            // parses the name parameter.
            OpenConnector(name string) (Connector, error)
        }

        type Execer

        Execer is an optional interface that may be implemented by a Conn.

        If a Conn implements neither ExecerContext nor Execer, the database/sql.DB.Exec will first prepare a query, execute the statement, and then close the statement.

        Exec may return ErrSkip.

        Deprecated: Drivers should implement ExecerContext instead.

        type Execer interface {
            Exec(query string, args []Value) (Result, error)
        }

        type ExecerContext

        ExecerContext is an optional interface that may be implemented by a Conn.

        If a Conn does not implement ExecerContext, the database/sql.DB.Exec will fall back to Execer; if the Conn does not implement Execer either, database/sql.DB.Exec will first prepare a query, execute the statement, and then close the statement.

        ExecContext may return ErrSkip.

        ExecContext must honor the context timeout and return when the context is canceled.

        type ExecerContext interface {
            ExecContext(ctx context.Context, query string, args []NamedValue) (Result, error)
        }

        type IsolationLevel

        IsolationLevel is the transaction isolation level stored in TxOptions.

        This type should be considered identical to database/sql.IsolationLevel along with any values defined on it.

        type IsolationLevel int

        type NamedValue

        NamedValue holds both the value name and value.

        type NamedValue struct {
            // If the Name is not empty it should be used for the parameter identifier and
            // not the ordinal position.
            //
            // Name will not have a symbol prefix.
            Name string
        
            // Ordinal position of the parameter starting from one and is always set.
            Ordinal int
        
            // Value is the parameter value.
            Value Value
        }
        

        type NamedValueChecker

        NamedValueChecker may be optionally implemented by Conn or Stmt. It provides the driver more control to handle Go and database types beyond the default Value types allowed.

        The database/sql package checks for value checkers in the following order, stopping at the first found match: Stmt.NamedValueChecker, Conn.NamedValueChecker, Stmt.ColumnConverter, DefaultParameterConverter.

        If CheckNamedValue returns ErrRemoveArgument, the NamedValue will not be included in the final query arguments. This may be used to pass special options to the query itself.

        If ErrSkip is returned the column converter error checking path is used for the argument. Drivers may wish to return ErrSkip after they have exhausted their own special cases.

        type NamedValueChecker interface {
            // CheckNamedValue is called before passing arguments to the driver
            // and is called in place of any ColumnConverter. CheckNamedValue must do type
            // validation and conversion as appropriate for the driver.
            CheckNamedValue(*NamedValue) error
        }

        type NotNull

        NotNull is a type that implements ValueConverter by disallowing nil values but otherwise delegating to another ValueConverter.

        type NotNull struct {
            Converter ValueConverter
        }
        

        func (NotNull) ConvertValue

        func (n NotNull) ConvertValue(v any) (Value, error)

        type Null

        Null is a type that implements ValueConverter by allowing nil values but otherwise delegating to another ValueConverter.

        type Null struct {
            Converter ValueConverter
        }
        

        func (Null) ConvertValue

        func (n Null) ConvertValue(v any) (Value, error)

        type Pinger

        Pinger is an optional interface that may be implemented by a Conn.

        If a Conn does not implement Pinger, the database/sql.DB.Ping and database/sql.DB.PingContext will check if there is at least one Conn available.

        If Conn.Ping returns ErrBadConn, database/sql.DB.Ping and database/sql.DB.PingContext will remove the Conn from pool.

        type Pinger interface {
            Ping(ctx context.Context) error
        }

        type Queryer

        Queryer is an optional interface that may be implemented by a Conn.

        If a Conn implements neither QueryerContext nor Queryer, the database/sql.DB.Query will first prepare a query, execute the statement, and then close the statement.

        Query may return ErrSkip.

        Deprecated: Drivers should implement QueryerContext instead.

        type Queryer interface {
            Query(query string, args []Value) (Rows, error)
        }

        type QueryerContext

        QueryerContext is an optional interface that may be implemented by a Conn.

        If a Conn does not implement QueryerContext, the database/sql.DB.Query will fall back to Queryer; if the Conn does not implement Queryer either, database/sql.DB.Query will first prepare a query, execute the statement, and then close the statement.

        QueryContext may return ErrSkip.

        QueryContext must honor the context timeout and return when the context is canceled.

        type QueryerContext interface {
            QueryContext(ctx context.Context, query string, args []NamedValue) (Rows, error)
        }

        type Result

        Result is the result of a query execution.

        type Result interface {
            // LastInsertId returns the database's auto-generated ID
            // after, for example, an INSERT into a table with primary
            // key.
            LastInsertId() (int64, error)
        
            // RowsAffected returns the number of rows affected by the
            // query.
            RowsAffected() (int64, error)
        }

        type Rows

        Rows is an iterator over an executed query's results.

        type Rows interface {
            // Columns returns the names of the columns. The number of
            // columns of the result is inferred from the length of the
            // slice. If a particular column name isn't known, an empty
            // string should be returned for that entry.
            Columns() []string
        
            // Close closes the rows iterator.
            Close() error
        
            // Next is called to populate the next row of data into
            // the provided slice. The provided slice will be the same
            // size as the Columns() are wide.
            //
            // Next should return io.EOF when there are no more rows.
            //
            // The dest should not be written to outside of Next. Care
            // should be taken when closing Rows not to modify
            // a buffer held in dest.
            Next(dest []Value) error
        }

        type RowsAffected

        RowsAffected implements Result for an INSERT or UPDATE operation which mutates a number of rows.

        type RowsAffected int64

        func (RowsAffected) LastInsertId

        func (RowsAffected) LastInsertId() (int64, error)

        func (RowsAffected) RowsAffected

        func (v RowsAffected) RowsAffected() (int64, error)

        type RowsColumnTypeDatabaseTypeName

        RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the database system type name without the length. Type names should be uppercase. Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT", "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML", "TIMESTAMP".

        type RowsColumnTypeDatabaseTypeName interface {
            Rows
            ColumnTypeDatabaseTypeName(index int) string
        }

        type RowsColumnTypeLength

        RowsColumnTypeLength may be implemented by Rows. It should return the length of the column type if the column is a variable length type. If the column is not a variable length type ok should return false. If length is not limited other than system limits, it should return math.MaxInt64. The following are examples of returned values for various types:

        TEXT          (math.MaxInt64, true)
        varchar(10)   (10, true)
        nvarchar(10)  (10, true)
        decimal       (0, false)
        int           (0, false)
        bytea(30)     (30, true)
        
        type RowsColumnTypeLength interface {
            Rows
            ColumnTypeLength(index int) (length int64, ok bool)
        }

        type RowsColumnTypeNullable

        RowsColumnTypeNullable may be implemented by Rows. The nullable value should be true if it is known the column may be null, or false if the column is known to be not nullable. If the column nullability is unknown, ok should be false.

        type RowsColumnTypeNullable interface {
            Rows
            ColumnTypeNullable(index int) (nullable, ok bool)
        }

        type RowsColumnTypePrecisionScale

        RowsColumnTypePrecisionScale may be implemented by Rows. It should return the precision and scale for decimal types. If not applicable, ok should be false. The following are examples of returned values for various types:

        decimal(38, 4)    (38, 4, true)
        int               (0, 0, false)
        decimal           (math.MaxInt64, math.MaxInt64, true)
        
        type RowsColumnTypePrecisionScale interface {
            Rows
            ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool)
        }

        type RowsColumnTypeScanType

        RowsColumnTypeScanType may be implemented by Rows. It should return the value type that can be used to scan types into. For example, the database column type "bigint" this should return "reflect.TypeOf(int64(0))".

        type RowsColumnTypeScanType interface {
            Rows
            ColumnTypeScanType(index int) reflect.Type
        }

        type RowsNextResultSet

        RowsNextResultSet extends the Rows interface by providing a way to signal the driver to advance to the next result set.

        type RowsNextResultSet interface {
            Rows
        
            // HasNextResultSet is called at the end of the current result set and
            // reports whether there is another result set after the current one.
            HasNextResultSet() bool
        
            // NextResultSet advances the driver to the next result set even
            // if there are remaining rows in the current result set.
            //
            // NextResultSet should return io.EOF when there are no more result sets.
            NextResultSet() error
        }

        type SessionResetter

        SessionResetter may be implemented by Conn to allow drivers to reset the session state associated with the connection and to signal a bad connection.

        type SessionResetter interface {
            // ResetSession is called prior to executing a query on the connection
            // if the connection has been used before. If the driver returns ErrBadConn
            // the connection is discarded.
            ResetSession(ctx context.Context) error
        }

        type Stmt

        Stmt is a prepared statement. It is bound to a Conn and not used by multiple goroutines concurrently.

        type Stmt interface {
            // Close closes the statement.
            //
            // As of Go 1.1, a Stmt will not be closed if it's in use
            // by any queries.
            //
            // Drivers must ensure all network calls made by Close
            // do not block indefinitely (e.g. apply a timeout).
            Close() error
        
            // NumInput returns the number of placeholder parameters.
            //
            // If NumInput returns >= 0, the sql package will sanity check
            // argument counts from callers and return errors to the caller
            // before the statement's Exec or Query methods are called.
            //
            // NumInput may also return -1, if the driver doesn't know
            // its number of placeholders. In that case, the sql package
            // will not sanity check Exec or Query argument counts.
            NumInput() int
        
            // Exec executes a query that doesn't return rows, such
            // as an INSERT or UPDATE.
            //
            // Deprecated: Drivers should implement StmtExecContext instead (or additionally).
            Exec(args []Value) (Result, error)
        
            // Query executes a query that may return rows, such as a
            // SELECT.
            //
            // Deprecated: Drivers should implement StmtQueryContext instead (or additionally).
            Query(args []Value) (Rows, error)
        }

        type StmtExecContext

        StmtExecContext enhances the Stmt interface by providing Exec with context.

        type StmtExecContext interface {
            // ExecContext executes a query that doesn't return rows, such
            // as an INSERT or UPDATE.
            //
            // ExecContext must honor the context timeout and return when it is canceled.
            ExecContext(ctx context.Context, args []NamedValue) (Result, error)
        }

        type StmtQueryContext

        StmtQueryContext enhances the Stmt interface by providing Query with context.

        type StmtQueryContext interface {
            // QueryContext executes a query that may return rows, such as a
            // SELECT.
            //
            // QueryContext must honor the context timeout and return when it is canceled.
            QueryContext(ctx context.Context, args []NamedValue) (Rows, error)
        }

        type Tx

        Tx is a transaction.

        type Tx interface {
            Commit() error
            Rollback() error
        }

        type TxOptions

        TxOptions holds the transaction options.

        This type should be considered identical to database/sql.TxOptions.

        type TxOptions struct {
            Isolation IsolationLevel
            ReadOnly  bool
        }
        

        type Validator

        Validator may be implemented by Conn to allow drivers to signal if a connection is valid or if it should be discarded.

        If implemented, drivers may return the underlying error from queries, even if the connection should be discarded by the connection pool.

        type Validator interface {
            // IsValid is called prior to placing the connection into the
            // connection pool. The connection will be discarded if false is returned.
            IsValid() bool
        }

        type Value

        Value is a value that drivers must be able to handle. It is either nil, a type handled by a database driver's NamedValueChecker interface, or an instance of one of these types:

        int64
        float64
        bool
        []byte
        string
        time.Time
        

        If the driver supports cursors, a returned Value may also implement the Rows interface in this package. This is used, for example, when a user selects a cursor such as "select cursor(select * from my_table) from dual". If the Rows from the select is closed, the cursor Rows will also be closed.

        type Value any

        type ValueConverter

        ValueConverter is the interface providing the ConvertValue method.

        Various implementations of ValueConverter are provided by the driver package to provide consistent implementations of conversions between drivers. The ValueConverters have several uses:

        • converting from the Value types as provided by the sql package into a database table's specific column type and making sure it fits, such as making sure a particular int64 fits in a table's uint16 column.

        • converting a value as given from the database into one of the driver Value types.

        • by the database/sql package, for converting from a driver's Value type to a user's type in a scan.

        type ValueConverter interface {
            // ConvertValue converts a value to a driver Value.
            ConvertValue(v any) (Value, error)
        }

        type Valuer

        Valuer is the interface providing the Value method.

        Types implementing Valuer interface are able to convert themselves to a driver Value.

        type Valuer interface {
            // Value returns a driver Value.
            // Value must not panic.
            Value() (Value, error)
        }
        /src/debug - Go Documentation Server
        ...

        Directory /src/debug

        Name Synopsis
        ..
        buildinfo Package buildinfo provides access to information embedded in a Go binary about how it was built.
        dwarf Package dwarf provides access to DWARF debugging information loaded from executable files, as defined in the DWARF 2.0 Standard at http://dwarfstd.org/doc/dwarf-2.0.0.pdf.
        elf Package elf implements access to ELF object files.
        gosym Package gosym implements access to the Go symbol and line number tables embedded in Go binaries generated by the gc compilers.
        macho Package macho implements access to Mach-O object files.
        pe Package pe implements access to PE (Microsoft Windows Portable Executable) files.
        plan9obj Package plan9obj implements access to Plan 9 a.out object files.
        buildinfo - Go Documentation Server
        ...

        Package buildinfo

        import "debug/buildinfo"
        Overview
        Index

        Overview ▾

        Package buildinfo provides access to information embedded in a Go binary about how it was built. This includes the Go toolchain version, and the set of modules used (for binaries built in module mode).

        Build information is available for the currently running binary in runtime/debug.ReadBuildInfo.

        type BuildInfo

        Type alias for build info. We cannot move the types here, since runtime/debug would need to import this package, which would make it a much larger dependency.

        type BuildInfo = debug.BuildInfo

        func Read

        func Read(r io.ReaderAt) (*BuildInfo, error)

        Read returns build information embedded in a Go binary file accessed through the given ReaderAt. Most information is only available for binaries built with module support.

        func ReadFile

        func ReadFile(name string) (info *BuildInfo, err error)

        ReadFile returns build information embedded in a Go binary file at the given path. Most information is only available for binaries built with module support.

        dwarf - Go Documentation Server
        ...

        Package dwarf

        import "debug/dwarf"
        Overview
        Index

        Overview ▾

        Package dwarf provides access to DWARF debugging information loaded from executable files, as defined in the DWARF 2.0 Standard at http://dwarfstd.org/doc/dwarf-2.0.0.pdf.

        Security

        This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

        Index ▾

        Variables
        type AddrType
        type ArrayType
            func (t *ArrayType) Size() int64
            func (t *ArrayType) String() string
        type Attr
            func (a Attr) GoString() string
            func (i Attr) String() string
        type BasicType
            func (b *BasicType) Basic() *BasicType
            func (t *BasicType) String() string
        type BoolType
        type CharType
        type Class
            func (i Class) GoString() string
            func (i Class) String() string
        type CommonType
            func (c *CommonType) Common() *CommonType
            func (c *CommonType) Size() int64
        type ComplexType
        type Data
            func New(abbrev, aranges, frame, info, line, pubnames, ranges, str []byte) (*Data, error)
            func (d *Data) AddSection(name string, contents []byte) error
            func (d *Data) AddTypes(name string, types []byte) error
            func (d *Data) LineReader(cu *Entry) (*LineReader, error)
            func (d *Data) Ranges(e *Entry) ([][2]uint64, error)
            func (d *Data) Reader() *Reader
            func (d *Data) Type(off Offset) (Type, error)
        type DecodeError
            func (e DecodeError) Error() string
        type DotDotDotType
            func (t *DotDotDotType) String() string
        type Entry
            func (e *Entry) AttrField(a Attr) *Field
            func (e *Entry) Val(a Attr) any
        type EnumType
            func (t *EnumType) String() string
        type EnumValue
        type Field
        type FloatType
        type FuncType
            func (t *FuncType) String() string
        type IntType
        type LineEntry
        type LineFile
        type LineReader
            func (r *LineReader) Files() []*LineFile
            func (r *LineReader) Next(entry *LineEntry) error
            func (r *LineReader) Reset()
            func (r *LineReader) Seek(pos LineReaderPos)
            func (r *LineReader) SeekPC(pc uint64, entry *LineEntry) error
            func (r *LineReader) Tell() LineReaderPos
        type LineReaderPos
        type Offset
        type PtrType
            func (t *PtrType) String() string
        type QualType
            func (t *QualType) Size() int64
            func (t *QualType) String() string
        type Reader
            func (r *Reader) AddressSize() int
            func (r *Reader) ByteOrder() binary.ByteOrder
            func (r *Reader) Next() (*Entry, error)
            func (r *Reader) Seek(off Offset)
            func (r *Reader) SeekPC(pc uint64) (*Entry, error)
            func (r *Reader) SkipChildren()
        type StructField
        type StructType
            func (t *StructType) Defn() string
            func (t *StructType) String() string
        type Tag
            func (t Tag) GoString() string
            func (i Tag) String() string
        type Type
        type TypedefType
            func (t *TypedefType) Size() int64
            func (t *TypedefType) String() string
        type UcharType
        type UintType
        type UnspecifiedType
        type UnsupportedType
            func (t *UnsupportedType) String() string
        type VoidType
            func (t *VoidType) String() string

        Package files

        attr_string.go buf.go class_string.go const.go entry.go line.go open.go tag_string.go type.go typeunit.go unit.go

        Variables

        ErrUnknownPC is the error returned by LineReader.ScanPC when the seek PC is not covered by any entry in the line table.

        var ErrUnknownPC = errors.New("ErrUnknownPC")

        type AddrType

        An AddrType represents a machine address type.

        type AddrType struct {
            BasicType
        }
        

        type ArrayType

        An ArrayType represents a fixed size array type.

        type ArrayType struct {
            CommonType
            Type          Type
            StrideBitSize int64 // if > 0, number of bits to hold each element
            Count         int64 // if == -1, an incomplete array, like char x[].
        }
        

        func (*ArrayType) Size

        func (t *ArrayType) Size() int64

        func (*ArrayType) String

        func (t *ArrayType) String() string

        type Attr

        An Attr identifies the attribute type in a DWARF [Entry.Field].

        type Attr uint32
        const (
            AttrSibling        Attr = 0x01
            AttrLocation       Attr = 0x02
            AttrName           Attr = 0x03
            AttrOrdering       Attr = 0x09
            AttrByteSize       Attr = 0x0B
            AttrBitOffset      Attr = 0x0C
            AttrBitSize        Attr = 0x0D
            AttrStmtList       Attr = 0x10
            AttrLowpc          Attr = 0x11
            AttrHighpc         Attr = 0x12
            AttrLanguage       Attr = 0x13
            AttrDiscr          Attr = 0x15
            AttrDiscrValue     Attr = 0x16
            AttrVisibility     Attr = 0x17
            AttrImport         Attr = 0x18
            AttrStringLength   Attr = 0x19
            AttrCommonRef      Attr = 0x1A
            AttrCompDir        Attr = 0x1B
            AttrConstValue     Attr = 0x1C
            AttrContainingType Attr = 0x1D
            AttrDefaultValue   Attr = 0x1E
            AttrInline         Attr = 0x20
            AttrIsOptional     Attr = 0x21
            AttrLowerBound     Attr = 0x22
            AttrProducer       Attr = 0x25
            AttrPrototyped     Attr = 0x27
            AttrReturnAddr     Attr = 0x2A
            AttrStartScope     Attr = 0x2C
            AttrStrideSize     Attr = 0x2E
            AttrUpperBound     Attr = 0x2F
            AttrAbstractOrigin Attr = 0x31
            AttrAccessibility  Attr = 0x32
            AttrAddrClass      Attr = 0x33
            AttrArtificial     Attr = 0x34
            AttrBaseTypes      Attr = 0x35
            AttrCalling        Attr = 0x36
            AttrCount          Attr = 0x37
            AttrDataMemberLoc  Attr = 0x38
            AttrDeclColumn     Attr = 0x39
            AttrDeclFile       Attr = 0x3A
            AttrDeclLine       Attr = 0x3B
            AttrDeclaration    Attr = 0x3C
            AttrDiscrList      Attr = 0x3D
            AttrEncoding       Attr = 0x3E
            AttrExternal       Attr = 0x3F
            AttrFrameBase      Attr = 0x40
            AttrFriend         Attr = 0x41
            AttrIdentifierCase Attr = 0x42
            AttrMacroInfo      Attr = 0x43
            AttrNamelistItem   Attr = 0x44
            AttrPriority       Attr = 0x45
            AttrSegment        Attr = 0x46
            AttrSpecification  Attr = 0x47
            AttrStaticLink     Attr = 0x48
            AttrType           Attr = 0x49
            AttrUseLocation    Attr = 0x4A
            AttrVarParam       Attr = 0x4B
            AttrVirtuality     Attr = 0x4C
            AttrVtableElemLoc  Attr = 0x4D
            // The following are new in DWARF 3.
            AttrAllocated     Attr = 0x4E
            AttrAssociated    Attr = 0x4F
            AttrDataLocation  Attr = 0x50
            AttrStride        Attr = 0x51
            AttrEntrypc       Attr = 0x52
            AttrUseUTF8       Attr = 0x53
            AttrExtension     Attr = 0x54
            AttrRanges        Attr = 0x55
            AttrTrampoline    Attr = 0x56
            AttrCallColumn    Attr = 0x57
            AttrCallFile      Attr = 0x58
            AttrCallLine      Attr = 0x59
            AttrDescription   Attr = 0x5A
            AttrBinaryScale   Attr = 0x5B
            AttrDecimalScale  Attr = 0x5C
            AttrSmall         Attr = 0x5D
            AttrDecimalSign   Attr = 0x5E
            AttrDigitCount    Attr = 0x5F
            AttrPictureString Attr = 0x60
            AttrMutable       Attr = 0x61
            AttrThreadsScaled Attr = 0x62
            AttrExplicit      Attr = 0x63
            AttrObjectPointer Attr = 0x64
            AttrEndianity     Attr = 0x65
            AttrElemental     Attr = 0x66
            AttrPure          Attr = 0x67
            AttrRecursive     Attr = 0x68
            // The following are new in DWARF 4.
            AttrSignature      Attr = 0x69
            AttrMainSubprogram Attr = 0x6A
            AttrDataBitOffset  Attr = 0x6B
            AttrConstExpr      Attr = 0x6C
            AttrEnumClass      Attr = 0x6D
            AttrLinkageName    Attr = 0x6E
            // The following are new in DWARF 5.
            AttrStringLengthBitSize  Attr = 0x6F
            AttrStringLengthByteSize Attr = 0x70
            AttrRank                 Attr = 0x71
            AttrStrOffsetsBase       Attr = 0x72
            AttrAddrBase             Attr = 0x73
            AttrRnglistsBase         Attr = 0x74
            AttrDwoName              Attr = 0x76
            AttrReference            Attr = 0x77
            AttrRvalueReference      Attr = 0x78
            AttrMacros               Attr = 0x79
            AttrCallAllCalls         Attr = 0x7A
            AttrCallAllSourceCalls   Attr = 0x7B
            AttrCallAllTailCalls     Attr = 0x7C
            AttrCallReturnPC         Attr = 0x7D
            AttrCallValue            Attr = 0x7E
            AttrCallOrigin           Attr = 0x7F
            AttrCallParameter        Attr = 0x80
            AttrCallPC               Attr = 0x81
            AttrCallTailCall         Attr = 0x82
            AttrCallTarget           Attr = 0x83
            AttrCallTargetClobbered  Attr = 0x84
            AttrCallDataLocation     Attr = 0x85
            AttrCallDataValue        Attr = 0x86
            AttrNoreturn             Attr = 0x87
            AttrAlignment            Attr = 0x88
            AttrExportSymbols        Attr = 0x89
            AttrDeleted              Attr = 0x8A
            AttrDefaulted            Attr = 0x8B
            AttrLoclistsBase         Attr = 0x8C
        )

        func (Attr) GoString

        func (a Attr) GoString() string

        func (Attr) String

        func (i Attr) String() string

        type BasicType

        A BasicType holds fields common to all basic types.

        See the documentation for StructField for more info on the interpretation of the BitSize/BitOffset/DataBitOffset fields.

        type BasicType struct {
            CommonType
            BitSize       int64
            BitOffset     int64
            DataBitOffset int64
        }
        

        func (*BasicType) Basic

        func (b *BasicType) Basic() *BasicType

        func (*BasicType) String

        func (t *BasicType) String() string

        type BoolType

        A BoolType represents a boolean type.

        type BoolType struct {
            BasicType
        }
        

        type CharType

        A CharType represents a signed character type.

        type CharType struct {
            BasicType
        }
        

        type Class

        A Class is the DWARF 4 class of an attribute value.

        In general, a given attribute's value may take on one of several possible classes defined by DWARF, each of which leads to a slightly different interpretation of the attribute.

        DWARF version 4 distinguishes attribute value classes more finely than previous versions of DWARF. The reader will disambiguate coarser classes from earlier versions of DWARF into the appropriate DWARF 4 class. For example, DWARF 2 uses "constant" for constants as well as all types of section offsets, but the reader will canonicalize attributes in DWARF 2 files that refer to section offsets to one of the Class*Ptr classes, even though these classes were only defined in DWARF 3.

        type Class int
        const (
            // ClassUnknown represents values of unknown DWARF class.
            ClassUnknown Class = iota
        
            // ClassAddress represents values of type uint64 that are
            // addresses on the target machine.
            ClassAddress
        
            // ClassBlock represents values of type []byte whose
            // interpretation depends on the attribute.
            ClassBlock
        
            // ClassConstant represents values of type int64 that are
            // constants. The interpretation of this constant depends on
            // the attribute.
            ClassConstant
        
            // ClassExprLoc represents values of type []byte that contain
            // an encoded DWARF expression or location description.
            ClassExprLoc
        
            // ClassFlag represents values of type bool.
            ClassFlag
        
            // ClassLinePtr represents values that are an int64 offset
            // into the "line" section.
            ClassLinePtr
        
            // ClassLocListPtr represents values that are an int64 offset
            // into the "loclist" section.
            ClassLocListPtr
        
            // ClassMacPtr represents values that are an int64 offset into
            // the "mac" section.
            ClassMacPtr
        
            // ClassRangeListPtr represents values that are an int64 offset into
            // the "rangelist" section.
            ClassRangeListPtr
        
            // ClassReference represents values that are an Offset offset
            // of an Entry in the info section (for use with Reader.Seek).
            // The DWARF specification combines ClassReference and
            // ClassReferenceSig into class "reference".
            ClassReference
        
            // ClassReferenceSig represents values that are a uint64 type
            // signature referencing a type Entry.
            ClassReferenceSig
        
            // ClassString represents values that are strings. If the
            // compilation unit specifies the AttrUseUTF8 flag (strongly
            // recommended), the string value will be encoded in UTF-8.
            // Otherwise, the encoding is unspecified.
            ClassString
        
            // ClassReferenceAlt represents values of type int64 that are
            // an offset into the DWARF "info" section of an alternate
            // object file.
            ClassReferenceAlt
        
            // ClassStringAlt represents values of type int64 that are an
            // offset into the DWARF string section of an alternate object
            // file.
            ClassStringAlt
        
            // ClassAddrPtr represents values that are an int64 offset
            // into the "addr" section.
            ClassAddrPtr
        
            // ClassLocList represents values that are an int64 offset
            // into the "loclists" section.
            ClassLocList
        
            // ClassRngList represents values that are a uint64 offset
            // from the base of the "rnglists" section.
            ClassRngList
        
            // ClassRngListsPtr represents values that are an int64 offset
            // into the "rnglists" section. These are used as the base for
            // ClassRngList values.
            ClassRngListsPtr
        
            // ClassStrOffsetsPtr represents values that are an int64
            // offset into the "str_offsets" section.
            ClassStrOffsetsPtr
        )

        func (Class) GoString

        func (i Class) GoString() string

        func (Class) String

        func (i Class) String() string

        type CommonType

        A CommonType holds fields common to multiple types. If a field is not known or not applicable for a given type, the zero value is used.

        type CommonType struct {
            ByteSize int64  // size of value of this type, in bytes
            Name     string // name that can be used to refer to type
        }
        

        func (*CommonType) Common

        func (c *CommonType) Common() *CommonType

        func (*CommonType) Size

        func (c *CommonType) Size() int64

        type ComplexType

        A ComplexType represents a complex floating point type.

        type ComplexType struct {
            BasicType
        }
        

        type Data

        Data represents the DWARF debugging information loaded from an executable file (for example, an ELF or Mach-O executable).

        type Data struct {
            // contains filtered or unexported fields
        }
        

        func New

        func New(abbrev, aranges, frame, info, line, pubnames, ranges, str []byte) (*Data, error)

        New returns a new Data object initialized from the given parameters. Rather than calling this function directly, clients should typically use the DWARF method of the File type of the appropriate package debug/elf, debug/macho, or debug/pe.

        The []byte arguments are the data from the corresponding debug section in the object file; for example, for an ELF object, abbrev is the contents of the ".debug_abbrev" section.

        func (*Data) AddSection

        func (d *Data) AddSection(name string, contents []byte) error

        AddSection adds another DWARF section by name. The name should be a DWARF section name such as ".debug_addr", ".debug_str_offsets", and so forth. This approach is used for new DWARF sections added in DWARF 5 and later.

        func (*Data) AddTypes

        func (d *Data) AddTypes(name string, types []byte) error

        AddTypes will add one .debug_types section to the DWARF data. A typical object with DWARF version 4 debug info will have multiple .debug_types sections. The name is used for error reporting only, and serves to distinguish one .debug_types section from another.

        func (*Data) LineReader

        func (d *Data) LineReader(cu *Entry) (*LineReader, error)

        LineReader returns a new reader for the line table of compilation unit cu, which must be an Entry with tag TagCompileUnit.

        If this compilation unit has no line table, it returns nil, nil.

        func (*Data) Ranges

        func (d *Data) Ranges(e *Entry) ([][2]uint64, error)

        Ranges returns the PC ranges covered by e, a slice of [low,high) pairs. Only some entry types, such as TagCompileUnit or TagSubprogram, have PC ranges; for others, this will return nil with no error.

        func (*Data) Reader

        func (d *Data) Reader() *Reader

        Reader returns a new Reader for Data. The reader is positioned at byte offset 0 in the DWARF “info” section.

        func (*Data) Type

        func (d *Data) Type(off Offset) (Type, error)

        Type reads the type at off in the DWARF “info” section.

        type DecodeError

        type DecodeError struct {
            Name   string
            Offset Offset
            Err    string
        }
        

        func (DecodeError) Error

        func (e DecodeError) Error() string

        type DotDotDotType

        A DotDotDotType represents the variadic ... function parameter.

        type DotDotDotType struct {
            CommonType
        }
        

        func (*DotDotDotType) String

        func (t *DotDotDotType) String() string

        type Entry

        An entry is a sequence of attribute/value pairs.

        type Entry struct {
            Offset   Offset // offset of Entry in DWARF info
            Tag      Tag    // tag (kind of Entry)
            Children bool   // whether Entry is followed by children
            Field    []Field
        }
        

        func (*Entry) AttrField

        func (e *Entry) AttrField(a Attr) *Field

        AttrField returns the Field associated with attribute Attr in Entry, or nil if there is no such attribute.

        func (*Entry) Val

        func (e *Entry) Val(a Attr) any

        Val returns the value associated with attribute Attr in Entry, or nil if there is no such attribute.

        A common idiom is to merge the check for nil return with the check that the value has the expected dynamic type, as in:

        v, ok := e.Val(AttrSibling).(int64)
        

        type EnumType

        An EnumType represents an enumerated type. The only indication of its native integer type is its ByteSize (inside CommonType).

        type EnumType struct {
            CommonType
            EnumName string
            Val      []*EnumValue
        }
        

        func (*EnumType) String

        func (t *EnumType) String() string

        type EnumValue

        An EnumValue represents a single enumeration value.

        type EnumValue struct {
            Name string
            Val  int64
        }
        

        type Field

        A Field is a single attribute/value pair in an Entry.

        A value can be one of several "attribute classes" defined by DWARF. The Go types corresponding to each class are:

        DWARF class       Go type        Class
        -----------       -------        -----
        address           uint64         ClassAddress
        block             []byte         ClassBlock
        constant          int64          ClassConstant
        flag              bool           ClassFlag
        reference
          to info         dwarf.Offset   ClassReference
          to type unit    uint64         ClassReferenceSig
        string            string         ClassString
        exprloc           []byte         ClassExprLoc
        lineptr           int64          ClassLinePtr
        loclistptr        int64          ClassLocListPtr
        macptr            int64          ClassMacPtr
        rangelistptr      int64          ClassRangeListPtr
        

        For unrecognized or vendor-defined attributes, Class may be ClassUnknown.

        type Field struct {
            Attr  Attr
            Val   any
            Class Class
        }
        

        type FloatType

        A FloatType represents a floating point type.

        type FloatType struct {
            BasicType
        }
        

        type FuncType

        A FuncType represents a function type.

        type FuncType struct {
            CommonType
            ReturnType Type
            ParamType  []Type
        }
        

        func (*FuncType) String

        func (t *FuncType) String() string

        type IntType

        An IntType represents a signed integer type.

        type IntType struct {
            BasicType
        }
        

        type LineEntry

        A LineEntry is a row in a DWARF line table.

        type LineEntry struct {
            // Address is the program-counter value of a machine
            // instruction generated by the compiler. This LineEntry
            // applies to each instruction from Address to just before the
            // Address of the next LineEntry.
            Address uint64
        
            // OpIndex is the index of an operation within a VLIW
            // instruction. The index of the first operation is 0. For
            // non-VLIW architectures, it will always be 0. Address and
            // OpIndex together form an operation pointer that can
            // reference any individual operation within the instruction
            // stream.
            OpIndex int
        
            // File is the source file corresponding to these
            // instructions.
            File *LineFile
        
            // Line is the source code line number corresponding to these
            // instructions. Lines are numbered beginning at 1. It may be
            // 0 if these instructions cannot be attributed to any source
            // line.
            Line int
        
            // Column is the column number within the source line of these
            // instructions. Columns are numbered beginning at 1. It may
            // be 0 to indicate the "left edge" of the line.
            Column int
        
            // IsStmt indicates that Address is a recommended breakpoint
            // location, such as the beginning of a line, statement, or a
            // distinct subpart of a statement.
            IsStmt bool
        
            // BasicBlock indicates that Address is the beginning of a
            // basic block.
            BasicBlock bool
        
            // PrologueEnd indicates that Address is one (of possibly
            // many) PCs where execution should be suspended for a
            // breakpoint on entry to the containing function.
            //
            // Added in DWARF 3.
            PrologueEnd bool
        
            // EpilogueBegin indicates that Address is one (of possibly
            // many) PCs where execution should be suspended for a
            // breakpoint on exit from this function.
            //
            // Added in DWARF 3.
            EpilogueBegin bool
        
            // ISA is the instruction set architecture for these
            // instructions. Possible ISA values should be defined by the
            // applicable ABI specification.
            //
            // Added in DWARF 3.
            ISA int
        
            // Discriminator is an arbitrary integer indicating the block
            // to which these instructions belong. It serves to
            // distinguish among multiple blocks that may all have with
            // the same source file, line, and column. Where only one
            // block exists for a given source position, it should be 0.
            //
            // Added in DWARF 3.
            Discriminator int
        
            // EndSequence indicates that Address is the first byte after
            // the end of a sequence of target machine instructions. If it
            // is set, only this and the Address field are meaningful. A
            // line number table may contain information for multiple
            // potentially disjoint instruction sequences. The last entry
            // in a line table should always have EndSequence set.
            EndSequence bool
        }
        

        type LineFile

        A LineFile is a source file referenced by a DWARF line table entry.

        type LineFile struct {
            Name   string
            Mtime  uint64 // Implementation defined modification time, or 0 if unknown
            Length int    // File length, or 0 if unknown
        }
        

        type LineReader

        A LineReader reads a sequence of LineEntry structures from a DWARF "line" section for a single compilation unit. LineEntries occur in order of increasing PC and each LineEntry gives metadata for the instructions from that LineEntry's PC to just before the next LineEntry's PC. The last entry will have the [LineEntry.EndSequence] field set.

        type LineReader struct {
            // contains filtered or unexported fields
        }
        

        func (*LineReader) Files

        func (r *LineReader) Files() []*LineFile

        Files returns the file name table of this compilation unit as of the current position in the line table. The file name table may be referenced from attributes in this compilation unit such as AttrDeclFile.

        Entry 0 is always nil, since file index 0 represents "no file".

        The file name table of a compilation unit is not fixed. Files returns the file table as of the current position in the line table. This may contain more entries than the file table at an earlier position in the line table, though existing entries never change.

        func (*LineReader) Next

        func (r *LineReader) Next(entry *LineEntry) error

        Next sets *entry to the next row in this line table and moves to the next row. If there are no more entries and the line table is properly terminated, it returns io.EOF.

        Rows are always in order of increasing entry.Address, but entry.Line may go forward or backward.

        func (*LineReader) Reset

        func (r *LineReader) Reset()

        Reset repositions the line table reader at the beginning of the line table.

        func (*LineReader) Seek

        func (r *LineReader) Seek(pos LineReaderPos)

        Seek restores the line table reader to a position returned by LineReader.Tell.

        The argument pos must have been returned by a call to LineReader.Tell on this line table.

        func (*LineReader) SeekPC

        func (r *LineReader) SeekPC(pc uint64, entry *LineEntry) error

        SeekPC sets *entry to the LineEntry that includes pc and positions the reader on the next entry in the line table. If necessary, this will seek backwards to find pc.

        If pc is not covered by any entry in this line table, SeekPC returns ErrUnknownPC. In this case, *entry and the final seek position are unspecified.

        Note that DWARF line tables only permit sequential, forward scans. Hence, in the worst case, this takes time linear in the size of the line table. If the caller wishes to do repeated fast PC lookups, it should build an appropriate index of the line table.

        func (*LineReader) Tell

        func (r *LineReader) Tell() LineReaderPos

        Tell returns the current position in the line table.

        type LineReaderPos

        A LineReaderPos represents a position in a line table.

        type LineReaderPos struct {
            // contains filtered or unexported fields
        }
        

        type Offset

        An Offset represents the location of an Entry within the DWARF info. (See Reader.Seek.)

        type Offset uint32

        type PtrType

        A PtrType represents a pointer type.

        type PtrType struct {
            CommonType
            Type Type
        }
        

        func (*PtrType) String

        func (t *PtrType) String() string

        type QualType

        A QualType represents a type that has the C/C++ "const", "restrict", or "volatile" qualifier.

        type QualType struct {
            CommonType
            Qual string
            Type Type
        }
        

        func (*QualType) Size

        func (t *QualType) Size() int64

        func (*QualType) String

        func (t *QualType) String() string

        type Reader

        A Reader allows reading Entry structures from a DWARF “info” section. The Entry structures are arranged in a tree. The Reader.Next function return successive entries from a pre-order traversal of the tree. If an entry has children, its Children field will be true, and the children follow, terminated by an Entry with Tag 0.

        type Reader struct {
            // contains filtered or unexported fields
        }
        

        func (*Reader) AddressSize

        func (r *Reader) AddressSize() int

        AddressSize returns the size in bytes of addresses in the current compilation unit.

        func (*Reader) ByteOrder

        func (r *Reader) ByteOrder() binary.ByteOrder

        ByteOrder returns the byte order in the current compilation unit.

        func (*Reader) Next

        func (r *Reader) Next() (*Entry, error)

        Next reads the next entry from the encoded entry stream. It returns nil, nil when it reaches the end of the section. It returns an error if the current offset is invalid or the data at the offset cannot be decoded as a valid Entry.

        func (*Reader) Seek

        func (r *Reader) Seek(off Offset)

        Seek positions the Reader at offset off in the encoded entry stream. Offset 0 can be used to denote the first entry.

        func (*Reader) SeekPC

        func (r *Reader) SeekPC(pc uint64) (*Entry, error)

        SeekPC returns the Entry for the compilation unit that includes pc, and positions the reader to read the children of that unit. If pc is not covered by any unit, SeekPC returns ErrUnknownPC and the position of the reader is undefined.

        Because compilation units can describe multiple regions of the executable, in the worst case SeekPC must search through all the ranges in all the compilation units. Each call to SeekPC starts the search at the compilation unit of the last call, so in general looking up a series of PCs will be faster if they are sorted. If the caller wishes to do repeated fast PC lookups, it should build an appropriate index using the Ranges method.

        func (*Reader) SkipChildren

        func (r *Reader) SkipChildren()

        SkipChildren skips over the child entries associated with the last Entry returned by Reader.Next. If that Entry did not have children or Reader.Next has not been called, SkipChildren is a no-op.

        type StructField

        A StructField represents a field in a struct, union, or C++ class type.

        Bit Fields

        The BitSize, BitOffset, and DataBitOffset fields describe the bit size and offset of data members declared as bit fields in C/C++ struct/union/class types.

        BitSize is the number of bits in the bit field.

        DataBitOffset, if non-zero, is the number of bits from the start of the enclosing entity (e.g. containing struct/class/union) to the start of the bit field. This corresponds to the DW_AT_data_bit_offset DWARF attribute that was introduced in DWARF 4.

        BitOffset, if non-zero, is the number of bits between the most significant bit of the storage unit holding the bit field to the most significant bit of the bit field. Here "storage unit" is the type name before the bit field (for a field "unsigned x:17", the storage unit is "unsigned"). BitOffset values can vary depending on the endianness of the system. BitOffset corresponds to the DW_AT_bit_offset DWARF attribute that was deprecated in DWARF 4 and removed in DWARF 5.

        At most one of DataBitOffset and BitOffset will be non-zero; DataBitOffset/BitOffset will only be non-zero if BitSize is non-zero. Whether a C compiler uses one or the other will depend on compiler vintage and command line options.

        Here is an example of C/C++ bit field use, along with what to expect in terms of DWARF bit offset info. Consider this code:

        struct S {
        	int q;
        	int j:5;
        	int k:6;
        	int m:5;
        	int n:8;
        } s;
        

        For the code above, one would expect to see the following for DW_AT_bit_offset values (using GCC 8):

               Little   |     Big
               Endian   |    Endian
                        |
        "j":     27     |     0
        "k":     21     |     5
        "m":     16     |     11
        "n":     8      |     16
        

        Note that in the above the offsets are purely with respect to the containing storage unit for j/k/m/n -- these values won't vary based on the size of prior data members in the containing struct.

        If the compiler emits DW_AT_data_bit_offset, the expected values would be:

        "j":     32
        "k":     37
        "m":     43
        "n":     48
        

        Here the value 32 for "j" reflects the fact that the bit field is preceded by other data members (recall that DW_AT_data_bit_offset values are relative to the start of the containing struct). Hence DW_AT_data_bit_offset values can be quite large for structs with many fields.

        DWARF also allow for the possibility of base types that have non-zero bit size and bit offset, so this information is also captured for base types, but it is worth noting that it is not possible to trigger this behavior using mainstream languages.

        type StructField struct {
            Name          string
            Type          Type
            ByteOffset    int64
            ByteSize      int64 // usually zero; use Type.Size() for normal fields
            BitOffset     int64
            DataBitOffset int64
            BitSize       int64 // zero if not a bit field
        }
        

        type StructType

        A StructType represents a struct, union, or C++ class type.

        type StructType struct {
            CommonType
            StructName string
            Kind       string // "struct", "union", or "class".
            Field      []*StructField
            Incomplete bool // if true, struct, union, class is declared but not defined
        }
        

        func (*StructType) Defn

        func (t *StructType) Defn() string

        func (*StructType) String

        func (t *StructType) String() string

        type Tag

        A Tag is the classification (the type) of an Entry.

        type Tag uint32
        const (
            TagArrayType              Tag = 0x01
            TagClassType              Tag = 0x02
            TagEntryPoint             Tag = 0x03
            TagEnumerationType        Tag = 0x04
            TagFormalParameter        Tag = 0x05
            TagImportedDeclaration    Tag = 0x08
            TagLabel                  Tag = 0x0A
            TagLexDwarfBlock          Tag = 0x0B
            TagMember                 Tag = 0x0D
            TagPointerType            Tag = 0x0F
            TagReferenceType          Tag = 0x10
            TagCompileUnit            Tag = 0x11
            TagStringType             Tag = 0x12
            TagStructType             Tag = 0x13
            TagSubroutineType         Tag = 0x15
            TagTypedef                Tag = 0x16
            TagUnionType              Tag = 0x17
            TagUnspecifiedParameters  Tag = 0x18
            TagVariant                Tag = 0x19
            TagCommonDwarfBlock       Tag = 0x1A
            TagCommonInclusion        Tag = 0x1B
            TagInheritance            Tag = 0x1C
            TagInlinedSubroutine      Tag = 0x1D
            TagModule                 Tag = 0x1E
            TagPtrToMemberType        Tag = 0x1F
            TagSetType                Tag = 0x20
            TagSubrangeType           Tag = 0x21
            TagWithStmt               Tag = 0x22
            TagAccessDeclaration      Tag = 0x23
            TagBaseType               Tag = 0x24
            TagCatchDwarfBlock        Tag = 0x25
            TagConstType              Tag = 0x26
            TagConstant               Tag = 0x27
            TagEnumerator             Tag = 0x28
            TagFileType               Tag = 0x29
            TagFriend                 Tag = 0x2A
            TagNamelist               Tag = 0x2B
            TagNamelistItem           Tag = 0x2C
            TagPackedType             Tag = 0x2D
            TagSubprogram             Tag = 0x2E
            TagTemplateTypeParameter  Tag = 0x2F
            TagTemplateValueParameter Tag = 0x30
            TagThrownType             Tag = 0x31
            TagTryDwarfBlock          Tag = 0x32
            TagVariantPart            Tag = 0x33
            TagVariable               Tag = 0x34
            TagVolatileType           Tag = 0x35
            // The following are new in DWARF 3.
            TagDwarfProcedure  Tag = 0x36
            TagRestrictType    Tag = 0x37
            TagInterfaceType   Tag = 0x38
            TagNamespace       Tag = 0x39
            TagImportedModule  Tag = 0x3A
            TagUnspecifiedType Tag = 0x3B
            TagPartialUnit     Tag = 0x3C
            TagImportedUnit    Tag = 0x3D
            TagMutableType     Tag = 0x3E // Later removed from DWARF.
            TagCondition       Tag = 0x3F
            TagSharedType      Tag = 0x40
            // The following are new in DWARF 4.
            TagTypeUnit            Tag = 0x41
            TagRvalueReferenceType Tag = 0x42
            TagTemplateAlias       Tag = 0x43
            // The following are new in DWARF 5.
            TagCoarrayType       Tag = 0x44
            TagGenericSubrange   Tag = 0x45
            TagDynamicType       Tag = 0x46
            TagAtomicType        Tag = 0x47
            TagCallSite          Tag = 0x48
            TagCallSiteParameter Tag = 0x49
            TagSkeletonUnit      Tag = 0x4A
            TagImmutableType     Tag = 0x4B
        )

        func (Tag) GoString

        func (t Tag) GoString() string

        func (Tag) String

        func (i Tag) String() string

        type Type

        A Type conventionally represents a pointer to any of the specific Type structures (CharType, StructType, etc.).

        type Type interface {
            Common() *CommonType
            String() string
            Size() int64
        }

        type TypedefType

        A TypedefType represents a named type.

        type TypedefType struct {
            CommonType
            Type Type
        }
        

        func (*TypedefType) Size

        func (t *TypedefType) Size() int64

        func (*TypedefType) String

        func (t *TypedefType) String() string

        type UcharType

        A UcharType represents an unsigned character type.

        type UcharType struct {
            BasicType
        }
        

        type UintType

        A UintType represents an unsigned integer type.

        type UintType struct {
            BasicType
        }
        

        type UnspecifiedType

        An UnspecifiedType represents an implicit, unknown, ambiguous or nonexistent type.

        type UnspecifiedType struct {
            BasicType
        }
        

        type UnsupportedType

        An UnsupportedType is a placeholder returned in situations where we encounter a type that isn't supported.

        type UnsupportedType struct {
            CommonType
            Tag Tag
        }
        

        func (*UnsupportedType) String

        func (t *UnsupportedType) String() string

        type VoidType

        A VoidType represents the C void type.

        type VoidType struct {
            CommonType
        }
        

        func (*VoidType) String

        func (t *VoidType) String() string
        elf - Go Documentation Server
        ...

        Package elf

        import "debug/elf"
        Overview
        Index

        Overview ▾

        Package elf implements access to ELF object files.

        Security

        This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

        Index ▾

        Constants
        Variables
        func R_INFO(sym, typ uint32) uint64
        func R_INFO32(sym, typ uint32) uint32
        func R_SYM32(info uint32) uint32
        func R_SYM64(info uint64) uint32
        func R_TYPE32(info uint32) uint32
        func R_TYPE64(info uint64) uint32
        func ST_INFO(bind SymBind, typ SymType) uint8
        type Chdr32
        type Chdr64
        type Class
            func (i Class) GoString() string
            func (i Class) String() string
        type CompressionType
            func (i CompressionType) GoString() string
            func (i CompressionType) String() string
        type Data
            func (i Data) GoString() string
            func (i Data) String() string
        type Dyn32
        type Dyn64
        type DynFlag
            func (i DynFlag) GoString() string
            func (i DynFlag) String() string
        type DynFlag1
            func (i DynFlag1) GoString() string
            func (i DynFlag1) String() string
        type DynTag
            func (i DynTag) GoString() string
            func (i DynTag) String() string
        type File
            func NewFile(r io.ReaderAt) (*File, error)
            func Open(name string) (*File, error)
            func (f *File) Close() error
            func (f *File) DWARF() (*dwarf.Data, error)
            func (f *File) DynString(tag DynTag) ([]string, error)
            func (f *File) DynValue(tag DynTag) ([]uint64, error)
            func (f *File) DynamicSymbols() ([]Symbol, error)
            func (f *File) ImportedLibraries() ([]string, error)
            func (f *File) ImportedSymbols() ([]ImportedSymbol, error)
            func (f *File) Section(name string) *Section
            func (f *File) SectionByType(typ SectionType) *Section
            func (f *File) Symbols() ([]Symbol, error)
        type FileHeader
        type FormatError
            func (e *FormatError) Error() string
        type Header32
        type Header64
        type ImportedSymbol
        type Machine
            func (i Machine) GoString() string
            func (i Machine) String() string
        type NType
            func (i NType) GoString() string
            func (i NType) String() string
        type OSABI
            func (i OSABI) GoString() string
            func (i OSABI) String() string
        type Prog
            func (p *Prog) Open() io.ReadSeeker
        type Prog32
        type Prog64
        type ProgFlag
            func (i ProgFlag) GoString() string
            func (i ProgFlag) String() string
        type ProgHeader
        type ProgType
            func (i ProgType) GoString() string
            func (i ProgType) String() string
        type R_386
            func (i R_386) GoString() string
            func (i R_386) String() string
        type R_390
            func (i R_390) GoString() string
            func (i R_390) String() string
        type R_AARCH64
            func (i R_AARCH64) GoString() string
            func (i R_AARCH64) String() string
        type R_ALPHA
            func (i R_ALPHA) GoString() string
            func (i R_ALPHA) String() string
        type R_ARM
            func (i R_ARM) GoString() string
            func (i R_ARM) String() string
        type R_LARCH
            func (i R_LARCH) GoString() string
            func (i R_LARCH) String() string
        type R_MIPS
            func (i R_MIPS) GoString() string
            func (i R_MIPS) String() string
        type R_PPC
            func (i R_PPC) GoString() string
            func (i R_PPC) String() string
        type R_PPC64
            func (i R_PPC64) GoString() string
            func (i R_PPC64) String() string
        type R_RISCV
            func (i R_RISCV) GoString() string
            func (i R_RISCV) String() string
        type R_SPARC
            func (i R_SPARC) GoString() string
            func (i R_SPARC) String() string
        type R_X86_64
            func (i R_X86_64) GoString() string
            func (i R_X86_64) String() string
        type Rel32
        type Rel64
        type Rela32
        type Rela64
        type Section
            func (s *Section) Data() ([]byte, error)
            func (s *Section) Open() io.ReadSeeker
        type Section32
        type Section64
        type SectionFlag
            func (i SectionFlag) GoString() string
            func (i SectionFlag) String() string
        type SectionHeader
        type SectionIndex
            func (i SectionIndex) GoString() string
            func (i SectionIndex) String() string
        type SectionType
            func (i SectionType) GoString() string
            func (i SectionType) String() string
        type Sym32
        type Sym64
        type SymBind
            func ST_BIND(info uint8) SymBind
            func (i SymBind) GoString() string
            func (i SymBind) String() string
        type SymType
            func ST_TYPE(info uint8) SymType
            func (i SymType) GoString() string
            func (i SymType) String() string
        type SymVis
            func ST_VISIBILITY(other uint8) SymVis
            func (i SymVis) GoString() string
            func (i SymVis) String() string
        type Symbol
        type Type
            func (i Type) GoString() string
            func (i Type) String() string
        type Version
            func (i Version) GoString() string
            func (i Version) String() string

        Package files

        elf.go file.go reader.go

        Constants

        Indexes into the Header.Ident array.

        const (
            EI_CLASS      = 4  /* Class of machine. */
            EI_DATA       = 5  /* Data format. */
            EI_VERSION    = 6  /* ELF format version. */
            EI_OSABI      = 7  /* Operating system / ABI identification */
            EI_ABIVERSION = 8  /* ABI version */
            EI_PAD        = 9  /* Start of padding (per SVR4 ABI). */
            EI_NIDENT     = 16 /* Size of e_ident array. */
        )

        Magic number for the elf trampoline, chosen wisely to be an immediate value.

        const ARM_MAGIC_TRAMP_NUMBER = 0x5c000003

        Initial magic number for ELF files.

        const ELFMAG = "\177ELF"
        const Sym32Size = 16
        const Sym64Size = 24

        Variables

        ErrNoSymbols is returned by File.Symbols and File.DynamicSymbols if there is no such section in the File.

        var ErrNoSymbols = errors.New("no symbol section")

        func R_INFO

        func R_INFO(sym, typ uint32) uint64

        func R_INFO32

        func R_INFO32(sym, typ uint32) uint32

        func R_SYM32

        func R_SYM32(info uint32) uint32

        func R_SYM64

        func R_SYM64(info uint64) uint32

        func R_TYPE32

        func R_TYPE32(info uint32) uint32

        func R_TYPE64

        func R_TYPE64(info uint64) uint32

        func ST_INFO

        func ST_INFO(bind SymBind, typ SymType) uint8

        type Chdr32

        ELF32 Compression header.

        type Chdr32 struct {
            Type      uint32
            Size      uint32
            Addralign uint32
        }
        

        type Chdr64

        ELF64 Compression header.

        type Chdr64 struct {
            Type uint32
        
            Size      uint64
            Addralign uint64
            // contains filtered or unexported fields
        }
        

        type Class

        Class is found in Header.Ident[EI_CLASS] and Header.Class.

        type Class byte
        const (
            ELFCLASSNONE Class = 0 /* Unknown class. */
            ELFCLASS32   Class = 1 /* 32-bit architecture. */
            ELFCLASS64   Class = 2 /* 64-bit architecture. */
        )

        func (Class) GoString

        func (i Class) GoString() string

        func (Class) String

        func (i Class) String() string

        type CompressionType

        Section compression type.

        type CompressionType int
        const (
            COMPRESS_ZLIB   CompressionType = 1          /* ZLIB compression. */
            COMPRESS_ZSTD   CompressionType = 2          /* ZSTD compression. */
            COMPRESS_LOOS   CompressionType = 0x60000000 /* First OS-specific. */
            COMPRESS_HIOS   CompressionType = 0x6fffffff /* Last OS-specific. */
            COMPRESS_LOPROC CompressionType = 0x70000000 /* First processor-specific type. */
            COMPRESS_HIPROC CompressionType = 0x7fffffff /* Last processor-specific type. */
        )

        func (CompressionType) GoString

        func (i CompressionType) GoString() string

        func (CompressionType) String

        func (i CompressionType) String() string

        type Data

        Data is found in Header.Ident[EI_DATA] and Header.Data.

        type Data byte
        const (
            ELFDATANONE Data = 0 /* Unknown data format. */
            ELFDATA2LSB Data = 1 /* 2's complement little-endian. */
            ELFDATA2MSB Data = 2 /* 2's complement big-endian. */
        )

        func (Data) GoString

        func (i Data) GoString() string

        func (Data) String

        func (i Data) String() string

        type Dyn32

        ELF32 Dynamic structure. The ".dynamic" section contains an array of them.

        type Dyn32 struct {
            Tag int32  /* Entry type. */
            Val uint32 /* Integer/Address value. */
        }
        

        type Dyn64

        ELF64 Dynamic structure. The ".dynamic" section contains an array of them.

        type Dyn64 struct {
            Tag int64  /* Entry type. */
            Val uint64 /* Integer/address value */
        }
        

        type DynFlag

        DT_FLAGS values.

        type DynFlag int
        const (
            DF_ORIGIN DynFlag = 0x0001 /* Indicates that the object being loaded may
               make reference to the
               $ORIGIN substitution string */
            DF_SYMBOLIC DynFlag = 0x0002 /* Indicates "symbolic" linking. */
            DF_TEXTREL  DynFlag = 0x0004 /* Indicates there may be relocations in non-writable segments. */
            DF_BIND_NOW DynFlag = 0x0008 /* Indicates that the dynamic linker should
               process all relocations for the object
               containing this entry before transferring
               control to the program. */
            DF_STATIC_TLS DynFlag = 0x0010 /* Indicates that the shared object or
               executable contains code using a static
               thread-local storage scheme. */
        )

        func (DynFlag) GoString

        func (i DynFlag) GoString() string

        func (DynFlag) String

        func (i DynFlag) String() string

        type DynFlag1

        DT_FLAGS_1 values.

        type DynFlag1 uint32
        const (
            // Indicates that all relocations for this object must be processed before
            // returning control to the program.
            DF_1_NOW DynFlag1 = 0x00000001
            // Unused.
            DF_1_GLOBAL DynFlag1 = 0x00000002
            // Indicates that the object is a member of a group.
            DF_1_GROUP DynFlag1 = 0x00000004
            // Indicates that the object cannot be deleted from a process.
            DF_1_NODELETE DynFlag1 = 0x00000008
            // Meaningful only for filters. Indicates that all associated filtees be
            // processed immediately.
            DF_1_LOADFLTR DynFlag1 = 0x00000010
            // Indicates that this object's initialization section be run before any other
            // objects loaded.
            DF_1_INITFIRST DynFlag1 = 0x00000020
            // Indicates that the object cannot be added to a running process with dlopen.
            DF_1_NOOPEN DynFlag1 = 0x00000040
            // Indicates the object requires $ORIGIN processing.
            DF_1_ORIGIN DynFlag1 = 0x00000080
            // Indicates that the object should use direct binding information.
            DF_1_DIRECT DynFlag1 = 0x00000100
            // Unused.
            DF_1_TRANS DynFlag1 = 0x00000200
            // Indicates that the objects symbol table is to interpose before all symbols
            // except the primary load object, which is typically the executable.
            DF_1_INTERPOSE DynFlag1 = 0x00000400
            // Indicates that the search for dependencies of this object ignores any
            // default library search paths.
            DF_1_NODEFLIB DynFlag1 = 0x00000800
            // Indicates that this object is not dumped by dldump. Candidates are objects
            // with no relocations that might get included when generating alternative
            // objects using.
            DF_1_NODUMP DynFlag1 = 0x00001000
            // Identifies this object as a configuration alternative object generated by
            // crle. Triggers the runtime linker to search for a configuration file $ORIGIN/ld.config.app-name.
            DF_1_CONFALT DynFlag1 = 0x00002000
            // Meaningful only for filtees. Terminates a filters search for any
            // further filtees.
            DF_1_ENDFILTEE DynFlag1 = 0x00004000
            // Indicates that this object has displacement relocations applied.
            DF_1_DISPRELDNE DynFlag1 = 0x00008000
            // Indicates that this object has displacement relocations pending.
            DF_1_DISPRELPND DynFlag1 = 0x00010000
            // Indicates that this object contains symbols that cannot be directly
            // bound to.
            DF_1_NODIRECT DynFlag1 = 0x00020000
            // Reserved for internal use by the kernel runtime-linker.
            DF_1_IGNMULDEF DynFlag1 = 0x00040000
            // Reserved for internal use by the kernel runtime-linker.
            DF_1_NOKSYMS DynFlag1 = 0x00080000
            // Reserved for internal use by the kernel runtime-linker.
            DF_1_NOHDR DynFlag1 = 0x00100000
            // Indicates that this object has been edited or has been modified since the
            // objects original construction by the link-editor.
            DF_1_EDITED DynFlag1 = 0x00200000
            // Reserved for internal use by the kernel runtime-linker.
            DF_1_NORELOC DynFlag1 = 0x00400000
            // Indicates that the object contains individual symbols that should interpose
            // before all symbols except the primary load object, which is typically the
            // executable.
            DF_1_SYMINTPOSE DynFlag1 = 0x00800000
            // Indicates that the executable requires global auditing.
            DF_1_GLOBAUDIT DynFlag1 = 0x01000000
            // Indicates that the object defines, or makes reference to singleton symbols.
            DF_1_SINGLETON DynFlag1 = 0x02000000
            // Indicates that the object is a stub.
            DF_1_STUB DynFlag1 = 0x04000000
            // Indicates that the object is a position-independent executable.
            DF_1_PIE DynFlag1 = 0x08000000
            // Indicates that the object is a kernel module.
            DF_1_KMOD DynFlag1 = 0x10000000
            // Indicates that the object is a weak standard filter.
            DF_1_WEAKFILTER DynFlag1 = 0x20000000
            // Unused.
            DF_1_NOCOMMON DynFlag1 = 0x40000000
        )

        func (DynFlag1) GoString

        func (i DynFlag1) GoString() string

        func (DynFlag1) String

        func (i DynFlag1) String() string

        type DynTag

        Dyn.Tag

        type DynTag int
        const (
            DT_NULL         DynTag = 0  /* Terminating entry. */
            DT_NEEDED       DynTag = 1  /* String table offset of a needed shared library. */
            DT_PLTRELSZ     DynTag = 2  /* Total size in bytes of PLT relocations. */
            DT_PLTGOT       DynTag = 3  /* Processor-dependent address. */
            DT_HASH         DynTag = 4  /* Address of symbol hash table. */
            DT_STRTAB       DynTag = 5  /* Address of string table. */
            DT_SYMTAB       DynTag = 6  /* Address of symbol table. */
            DT_RELA         DynTag = 7  /* Address of ElfNN_Rela relocations. */
            DT_RELASZ       DynTag = 8  /* Total size of ElfNN_Rela relocations. */
            DT_RELAENT      DynTag = 9  /* Size of each ElfNN_Rela relocation entry. */
            DT_STRSZ        DynTag = 10 /* Size of string table. */
            DT_SYMENT       DynTag = 11 /* Size of each symbol table entry. */
            DT_INIT         DynTag = 12 /* Address of initialization function. */
            DT_FINI         DynTag = 13 /* Address of finalization function. */
            DT_SONAME       DynTag = 14 /* String table offset of shared object name. */
            DT_RPATH        DynTag = 15 /* String table offset of library path. [sup] */
            DT_SYMBOLIC     DynTag = 16 /* Indicates "symbolic" linking. [sup] */
            DT_REL          DynTag = 17 /* Address of ElfNN_Rel relocations. */
            DT_RELSZ        DynTag = 18 /* Total size of ElfNN_Rel relocations. */
            DT_RELENT       DynTag = 19 /* Size of each ElfNN_Rel relocation. */
            DT_PLTREL       DynTag = 20 /* Type of relocation used for PLT. */
            DT_DEBUG        DynTag = 21 /* Reserved (not used). */
            DT_TEXTREL      DynTag = 22 /* Indicates there may be relocations in non-writable segments. [sup] */
            DT_JMPREL       DynTag = 23 /* Address of PLT relocations. */
            DT_BIND_NOW     DynTag = 24 /* [sup] */
            DT_INIT_ARRAY   DynTag = 25 /* Address of the array of pointers to initialization functions */
            DT_FINI_ARRAY   DynTag = 26 /* Address of the array of pointers to termination functions */
            DT_INIT_ARRAYSZ DynTag = 27 /* Size in bytes of the array of initialization functions. */
            DT_FINI_ARRAYSZ DynTag = 28 /* Size in bytes of the array of termination functions. */
            DT_RUNPATH      DynTag = 29 /* String table offset of a null-terminated library search path string. */
            DT_FLAGS        DynTag = 30 /* Object specific flag values. */
            DT_ENCODING     DynTag = 32 /* Values greater than or equal to DT_ENCODING
               and less than DT_LOOS follow the rules for
               the interpretation of the d_un union
               as follows: even == 'd_ptr', even == 'd_val'
               or none */
            DT_PREINIT_ARRAY   DynTag = 32 /* Address of the array of pointers to pre-initialization functions. */
            DT_PREINIT_ARRAYSZ DynTag = 33 /* Size in bytes of the array of pre-initialization functions. */
            DT_SYMTAB_SHNDX    DynTag = 34 /* Address of SHT_SYMTAB_SHNDX section. */
        
            DT_LOOS DynTag = 0x6000000d /* First OS-specific */
            DT_HIOS DynTag = 0x6ffff000 /* Last OS-specific */
        
            DT_VALRNGLO       DynTag = 0x6ffffd00
            DT_GNU_PRELINKED  DynTag = 0x6ffffdf5
            DT_GNU_CONFLICTSZ DynTag = 0x6ffffdf6
            DT_GNU_LIBLISTSZ  DynTag = 0x6ffffdf7
            DT_CHECKSUM       DynTag = 0x6ffffdf8
            DT_PLTPADSZ       DynTag = 0x6ffffdf9
            DT_MOVEENT        DynTag = 0x6ffffdfa
            DT_MOVESZ         DynTag = 0x6ffffdfb
            DT_FEATURE        DynTag = 0x6ffffdfc
            DT_POSFLAG_1      DynTag = 0x6ffffdfd
            DT_SYMINSZ        DynTag = 0x6ffffdfe
            DT_SYMINENT       DynTag = 0x6ffffdff
            DT_VALRNGHI       DynTag = 0x6ffffdff
        
            DT_ADDRRNGLO    DynTag = 0x6ffffe00
            DT_GNU_HASH     DynTag = 0x6ffffef5
            DT_TLSDESC_PLT  DynTag = 0x6ffffef6
            DT_TLSDESC_GOT  DynTag = 0x6ffffef7
            DT_GNU_CONFLICT DynTag = 0x6ffffef8
            DT_GNU_LIBLIST  DynTag = 0x6ffffef9
            DT_CONFIG       DynTag = 0x6ffffefa
            DT_DEPAUDIT     DynTag = 0x6ffffefb
            DT_AUDIT        DynTag = 0x6ffffefc
            DT_PLTPAD       DynTag = 0x6ffffefd
            DT_MOVETAB      DynTag = 0x6ffffefe
            DT_SYMINFO      DynTag = 0x6ffffeff
            DT_ADDRRNGHI    DynTag = 0x6ffffeff
        
            DT_VERSYM     DynTag = 0x6ffffff0
            DT_RELACOUNT  DynTag = 0x6ffffff9
            DT_RELCOUNT   DynTag = 0x6ffffffa
            DT_FLAGS_1    DynTag = 0x6ffffffb
            DT_VERDEF     DynTag = 0x6ffffffc
            DT_VERDEFNUM  DynTag = 0x6ffffffd
            DT_VERNEED    DynTag = 0x6ffffffe
            DT_VERNEEDNUM DynTag = 0x6fffffff
        
            DT_LOPROC DynTag = 0x70000000 /* First processor-specific type. */
        
            DT_MIPS_RLD_VERSION           DynTag = 0x70000001
            DT_MIPS_TIME_STAMP            DynTag = 0x70000002
            DT_MIPS_ICHECKSUM             DynTag = 0x70000003
            DT_MIPS_IVERSION              DynTag = 0x70000004
            DT_MIPS_FLAGS                 DynTag = 0x70000005
            DT_MIPS_BASE_ADDRESS          DynTag = 0x70000006
            DT_MIPS_MSYM                  DynTag = 0x70000007
            DT_MIPS_CONFLICT              DynTag = 0x70000008
            DT_MIPS_LIBLIST               DynTag = 0x70000009
            DT_MIPS_LOCAL_GOTNO           DynTag = 0x7000000a
            DT_MIPS_CONFLICTNO            DynTag = 0x7000000b
            DT_MIPS_LIBLISTNO             DynTag = 0x70000010
            DT_MIPS_SYMTABNO              DynTag = 0x70000011
            DT_MIPS_UNREFEXTNO            DynTag = 0x70000012
            DT_MIPS_GOTSYM                DynTag = 0x70000013
            DT_MIPS_HIPAGENO              DynTag = 0x70000014
            DT_MIPS_RLD_MAP               DynTag = 0x70000016
            DT_MIPS_DELTA_CLASS           DynTag = 0x70000017
            DT_MIPS_DELTA_CLASS_NO        DynTag = 0x70000018
            DT_MIPS_DELTA_INSTANCE        DynTag = 0x70000019
            DT_MIPS_DELTA_INSTANCE_NO     DynTag = 0x7000001a
            DT_MIPS_DELTA_RELOC           DynTag = 0x7000001b
            DT_MIPS_DELTA_RELOC_NO        DynTag = 0x7000001c
            DT_MIPS_DELTA_SYM             DynTag = 0x7000001d
            DT_MIPS_DELTA_SYM_NO          DynTag = 0x7000001e
            DT_MIPS_DELTA_CLASSSYM        DynTag = 0x70000020
            DT_MIPS_DELTA_CLASSSYM_NO     DynTag = 0x70000021
            DT_MIPS_CXX_FLAGS             DynTag = 0x70000022
            DT_MIPS_PIXIE_INIT            DynTag = 0x70000023
            DT_MIPS_SYMBOL_LIB            DynTag = 0x70000024
            DT_MIPS_LOCALPAGE_GOTIDX      DynTag = 0x70000025
            DT_MIPS_LOCAL_GOTIDX          DynTag = 0x70000026
            DT_MIPS_HIDDEN_GOTIDX         DynTag = 0x70000027
            DT_MIPS_PROTECTED_GOTIDX      DynTag = 0x70000028
            DT_MIPS_OPTIONS               DynTag = 0x70000029
            DT_MIPS_INTERFACE             DynTag = 0x7000002a
            DT_MIPS_DYNSTR_ALIGN          DynTag = 0x7000002b
            DT_MIPS_INTERFACE_SIZE        DynTag = 0x7000002c
            DT_MIPS_RLD_TEXT_RESOLVE_ADDR DynTag = 0x7000002d
            DT_MIPS_PERF_SUFFIX           DynTag = 0x7000002e
            DT_MIPS_COMPACT_SIZE          DynTag = 0x7000002f
            DT_MIPS_GP_VALUE              DynTag = 0x70000030
            DT_MIPS_AUX_DYNAMIC           DynTag = 0x70000031
            DT_MIPS_PLTGOT                DynTag = 0x70000032
            DT_MIPS_RWPLT                 DynTag = 0x70000034
            DT_MIPS_RLD_MAP_REL           DynTag = 0x70000035
        
            DT_PPC_GOT DynTag = 0x70000000
            DT_PPC_OPT DynTag = 0x70000001
        
            DT_PPC64_GLINK DynTag = 0x70000000
            DT_PPC64_OPD   DynTag = 0x70000001
            DT_PPC64_OPDSZ DynTag = 0x70000002
            DT_PPC64_OPT   DynTag = 0x70000003
        
            DT_SPARC_REGISTER DynTag = 0x70000001
        
            DT_AUXILIARY DynTag = 0x7ffffffd
            DT_USED      DynTag = 0x7ffffffe
            DT_FILTER    DynTag = 0x7fffffff
        
            DT_HIPROC DynTag = 0x7fffffff /* Last processor-specific type. */
        )

        func (DynTag) GoString

        func (i DynTag) GoString() string

        func (DynTag) String

        func (i DynTag) String() string

        type File

        A File represents an open ELF file.

        type File struct {
            FileHeader
            Sections []*Section
            Progs    []*Prog
            // contains filtered or unexported fields
        }
        

        func NewFile

        func NewFile(r io.ReaderAt) (*File, error)

        NewFile creates a new File for accessing an ELF binary in an underlying reader. The ELF binary is expected to start at position 0 in the ReaderAt.

        func Open

        func Open(name string) (*File, error)

        Open opens the named file using os.Open and prepares it for use as an ELF binary.

        func (*File) Close

        func (f *File) Close() error

        Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

        func (*File) DWARF

        func (f *File) DWARF() (*dwarf.Data, error)

        func (*File) DynString

        func (f *File) DynString(tag DynTag) ([]string, error)

        DynString returns the strings listed for the given tag in the file's dynamic section.

        The tag must be one that takes string values: DT_NEEDED, DT_SONAME, DT_RPATH, or DT_RUNPATH.

        func (*File) DynValue

        func (f *File) DynValue(tag DynTag) ([]uint64, error)

        DynValue returns the values listed for the given tag in the file's dynamic section.

        func (*File) DynamicSymbols

        func (f *File) DynamicSymbols() ([]Symbol, error)

        DynamicSymbols returns the dynamic symbol table for f. The symbols will be listed in the order they appear in f.

        If f has a symbol version table, the returned File.Symbols will have initialized Version and Library fields.

        For compatibility with File.Symbols, File.DynamicSymbols omits the null symbol at index 0. After retrieving the symbols as symtab, an externally supplied index x corresponds to symtab[x-1], not symtab[x].

        func (*File) ImportedLibraries

        func (f *File) ImportedLibraries() ([]string, error)

        ImportedLibraries returns the names of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.

        func (*File) ImportedSymbols

        func (f *File) ImportedSymbols() ([]ImportedSymbol, error)

        ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time. It does not return weak symbols.

        func (*File) Section

        func (f *File) Section(name string) *Section

        Section returns a section with the given name, or nil if no such section exists.

        func (*File) SectionByType

        func (f *File) SectionByType(typ SectionType) *Section

        SectionByType returns the first section in f with the given type, or nil if there is no such section.

        func (*File) Symbols

        func (f *File) Symbols() ([]Symbol, error)

        Symbols returns the symbol table for f. The symbols will be listed in the order they appear in f.

        For compatibility with Go 1.0, Symbols omits the null symbol at index 0. After retrieving the symbols as symtab, an externally supplied index x corresponds to symtab[x-1], not symtab[x].

        type FileHeader

        A FileHeader represents an ELF file header.

        type FileHeader struct {
            Class      Class
            Data       Data
            Version    Version
            OSABI      OSABI
            ABIVersion uint8
            ByteOrder  binary.ByteOrder
            Type       Type
            Machine    Machine
            Entry      uint64
        }
        

        type FormatError

        type FormatError struct {
            // contains filtered or unexported fields
        }
        

        func (*FormatError) Error

        func (e *FormatError) Error() string

        type Header32

        ELF32 File header.

        type Header32 struct {
            Ident     [EI_NIDENT]byte /* File identification. */
            Type      uint16          /* File type. */
            Machine   uint16          /* Machine architecture. */
            Version   uint32          /* ELF format version. */
            Entry     uint32          /* Entry point. */
            Phoff     uint32          /* Program header file offset. */
            Shoff     uint32          /* Section header file offset. */
            Flags     uint32          /* Architecture-specific flags. */
            Ehsize    uint16          /* Size of ELF header in bytes. */
            Phentsize uint16          /* Size of program header entry. */
            Phnum     uint16          /* Number of program header entries. */
            Shentsize uint16          /* Size of section header entry. */
            Shnum     uint16          /* Number of section header entries. */
            Shstrndx  uint16          /* Section name strings section. */
        }
        

        type Header64

        ELF64 file header.

        type Header64 struct {
            Ident     [EI_NIDENT]byte /* File identification. */
            Type      uint16          /* File type. */
            Machine   uint16          /* Machine architecture. */
            Version   uint32          /* ELF format version. */
            Entry     uint64          /* Entry point. */
            Phoff     uint64          /* Program header file offset. */
            Shoff     uint64          /* Section header file offset. */
            Flags     uint32          /* Architecture-specific flags. */
            Ehsize    uint16          /* Size of ELF header in bytes. */
            Phentsize uint16          /* Size of program header entry. */
            Phnum     uint16          /* Number of program header entries. */
            Shentsize uint16          /* Size of section header entry. */
            Shnum     uint16          /* Number of section header entries. */
            Shstrndx  uint16          /* Section name strings section. */
        }
        

        type ImportedSymbol

        type ImportedSymbol struct {
            Name    string
            Version string
            Library string
        }
        

        type Machine

        Machine is found in Header.Machine.

        type Machine uint16
        const (
            EM_NONE          Machine = 0   /* Unknown machine. */
            EM_M32           Machine = 1   /* AT&T WE32100. */
            EM_SPARC         Machine = 2   /* Sun SPARC. */
            EM_386           Machine = 3   /* Intel i386. */
            EM_68K           Machine = 4   /* Motorola 68000. */
            EM_88K           Machine = 5   /* Motorola 88000. */
            EM_860           Machine = 7   /* Intel i860. */
            EM_MIPS          Machine = 8   /* MIPS R3000 Big-Endian only. */
            EM_S370          Machine = 9   /* IBM System/370. */
            EM_MIPS_RS3_LE   Machine = 10  /* MIPS R3000 Little-Endian. */
            EM_PARISC        Machine = 15  /* HP PA-RISC. */
            EM_VPP500        Machine = 17  /* Fujitsu VPP500. */
            EM_SPARC32PLUS   Machine = 18  /* SPARC v8plus. */
            EM_960           Machine = 19  /* Intel 80960. */
            EM_PPC           Machine = 20  /* PowerPC 32-bit. */
            EM_PPC64         Machine = 21  /* PowerPC 64-bit. */
            EM_S390          Machine = 22  /* IBM System/390. */
            EM_V800          Machine = 36  /* NEC V800. */
            EM_FR20          Machine = 37  /* Fujitsu FR20. */
            EM_RH32          Machine = 38  /* TRW RH-32. */
            EM_RCE           Machine = 39  /* Motorola RCE. */
            EM_ARM           Machine = 40  /* ARM. */
            EM_SH            Machine = 42  /* Hitachi SH. */
            EM_SPARCV9       Machine = 43  /* SPARC v9 64-bit. */
            EM_TRICORE       Machine = 44  /* Siemens TriCore embedded processor. */
            EM_ARC           Machine = 45  /* Argonaut RISC Core. */
            EM_H8_300        Machine = 46  /* Hitachi H8/300. */
            EM_H8_300H       Machine = 47  /* Hitachi H8/300H. */
            EM_H8S           Machine = 48  /* Hitachi H8S. */
            EM_H8_500        Machine = 49  /* Hitachi H8/500. */
            EM_IA_64         Machine = 50  /* Intel IA-64 Processor. */
            EM_MIPS_X        Machine = 51  /* Stanford MIPS-X. */
            EM_COLDFIRE      Machine = 52  /* Motorola ColdFire. */
            EM_68HC12        Machine = 53  /* Motorola M68HC12. */
            EM_MMA           Machine = 54  /* Fujitsu MMA. */
            EM_PCP           Machine = 55  /* Siemens PCP. */
            EM_NCPU          Machine = 56  /* Sony nCPU. */
            EM_NDR1          Machine = 57  /* Denso NDR1 microprocessor. */
            EM_STARCORE      Machine = 58  /* Motorola Star*Core processor. */
            EM_ME16          Machine = 59  /* Toyota ME16 processor. */
            EM_ST100         Machine = 60  /* STMicroelectronics ST100 processor. */
            EM_TINYJ         Machine = 61  /* Advanced Logic Corp. TinyJ processor. */
            EM_X86_64        Machine = 62  /* Advanced Micro Devices x86-64 */
            EM_PDSP          Machine = 63  /* Sony DSP Processor */
            EM_PDP10         Machine = 64  /* Digital Equipment Corp. PDP-10 */
            EM_PDP11         Machine = 65  /* Digital Equipment Corp. PDP-11 */
            EM_FX66          Machine = 66  /* Siemens FX66 microcontroller */
            EM_ST9PLUS       Machine = 67  /* STMicroelectronics ST9+ 8/16 bit microcontroller */
            EM_ST7           Machine = 68  /* STMicroelectronics ST7 8-bit microcontroller */
            EM_68HC16        Machine = 69  /* Motorola MC68HC16 Microcontroller */
            EM_68HC11        Machine = 70  /* Motorola MC68HC11 Microcontroller */
            EM_68HC08        Machine = 71  /* Motorola MC68HC08 Microcontroller */
            EM_68HC05        Machine = 72  /* Motorola MC68HC05 Microcontroller */
            EM_SVX           Machine = 73  /* Silicon Graphics SVx */
            EM_ST19          Machine = 74  /* STMicroelectronics ST19 8-bit microcontroller */
            EM_VAX           Machine = 75  /* Digital VAX */
            EM_CRIS          Machine = 76  /* Axis Communications 32-bit embedded processor */
            EM_JAVELIN       Machine = 77  /* Infineon Technologies 32-bit embedded processor */
            EM_FIREPATH      Machine = 78  /* Element 14 64-bit DSP Processor */
            EM_ZSP           Machine = 79  /* LSI Logic 16-bit DSP Processor */
            EM_MMIX          Machine = 80  /* Donald Knuth's educational 64-bit processor */
            EM_HUANY         Machine = 81  /* Harvard University machine-independent object files */
            EM_PRISM         Machine = 82  /* SiTera Prism */
            EM_AVR           Machine = 83  /* Atmel AVR 8-bit microcontroller */
            EM_FR30          Machine = 84  /* Fujitsu FR30 */
            EM_D10V          Machine = 85  /* Mitsubishi D10V */
            EM_D30V          Machine = 86  /* Mitsubishi D30V */
            EM_V850          Machine = 87  /* NEC v850 */
            EM_M32R          Machine = 88  /* Mitsubishi M32R */
            EM_MN10300       Machine = 89  /* Matsushita MN10300 */
            EM_MN10200       Machine = 90  /* Matsushita MN10200 */
            EM_PJ            Machine = 91  /* picoJava */
            EM_OPENRISC      Machine = 92  /* OpenRISC 32-bit embedded processor */
            EM_ARC_COMPACT   Machine = 93  /* ARC International ARCompact processor (old spelling/synonym: EM_ARC_A5) */
            EM_XTENSA        Machine = 94  /* Tensilica Xtensa Architecture */
            EM_VIDEOCORE     Machine = 95  /* Alphamosaic VideoCore processor */
            EM_TMM_GPP       Machine = 96  /* Thompson Multimedia General Purpose Processor */
            EM_NS32K         Machine = 97  /* National Semiconductor 32000 series */
            EM_TPC           Machine = 98  /* Tenor Network TPC processor */
            EM_SNP1K         Machine = 99  /* Trebia SNP 1000 processor */
            EM_ST200         Machine = 100 /* STMicroelectronics (www.st.com) ST200 microcontroller */
            EM_IP2K          Machine = 101 /* Ubicom IP2xxx microcontroller family */
            EM_MAX           Machine = 102 /* MAX Processor */
            EM_CR            Machine = 103 /* National Semiconductor CompactRISC microprocessor */
            EM_F2MC16        Machine = 104 /* Fujitsu F2MC16 */
            EM_MSP430        Machine = 105 /* Texas Instruments embedded microcontroller msp430 */
            EM_BLACKFIN      Machine = 106 /* Analog Devices Blackfin (DSP) processor */
            EM_SE_C33        Machine = 107 /* S1C33 Family of Seiko Epson processors */
            EM_SEP           Machine = 108 /* Sharp embedded microprocessor */
            EM_ARCA          Machine = 109 /* Arca RISC Microprocessor */
            EM_UNICORE       Machine = 110 /* Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University */
            EM_EXCESS        Machine = 111 /* eXcess: 16/32/64-bit configurable embedded CPU */
            EM_DXP           Machine = 112 /* Icera Semiconductor Inc. Deep Execution Processor */
            EM_ALTERA_NIOS2  Machine = 113 /* Altera Nios II soft-core processor */
            EM_CRX           Machine = 114 /* National Semiconductor CompactRISC CRX microprocessor */
            EM_XGATE         Machine = 115 /* Motorola XGATE embedded processor */
            EM_C166          Machine = 116 /* Infineon C16x/XC16x processor */
            EM_M16C          Machine = 117 /* Renesas M16C series microprocessors */
            EM_DSPIC30F      Machine = 118 /* Microchip Technology dsPIC30F Digital Signal Controller */
            EM_CE            Machine = 119 /* Freescale Communication Engine RISC core */
            EM_M32C          Machine = 120 /* Renesas M32C series microprocessors */
            EM_TSK3000       Machine = 131 /* Altium TSK3000 core */
            EM_RS08          Machine = 132 /* Freescale RS08 embedded processor */
            EM_SHARC         Machine = 133 /* Analog Devices SHARC family of 32-bit DSP processors */
            EM_ECOG2         Machine = 134 /* Cyan Technology eCOG2 microprocessor */
            EM_SCORE7        Machine = 135 /* Sunplus S+core7 RISC processor */
            EM_DSP24         Machine = 136 /* New Japan Radio (NJR) 24-bit DSP Processor */
            EM_VIDEOCORE3    Machine = 137 /* Broadcom VideoCore III processor */
            EM_LATTICEMICO32 Machine = 138 /* RISC processor for Lattice FPGA architecture */
            EM_SE_C17        Machine = 139 /* Seiko Epson C17 family */
            EM_TI_C6000      Machine = 140 /* The Texas Instruments TMS320C6000 DSP family */
            EM_TI_C2000      Machine = 141 /* The Texas Instruments TMS320C2000 DSP family */
            EM_TI_C5500      Machine = 142 /* The Texas Instruments TMS320C55x DSP family */
            EM_TI_ARP32      Machine = 143 /* Texas Instruments Application Specific RISC Processor, 32bit fetch */
            EM_TI_PRU        Machine = 144 /* Texas Instruments Programmable Realtime Unit */
            EM_MMDSP_PLUS    Machine = 160 /* STMicroelectronics 64bit VLIW Data Signal Processor */
            EM_CYPRESS_M8C   Machine = 161 /* Cypress M8C microprocessor */
            EM_R32C          Machine = 162 /* Renesas R32C series microprocessors */
            EM_TRIMEDIA      Machine = 163 /* NXP Semiconductors TriMedia architecture family */
            EM_QDSP6         Machine = 164 /* QUALCOMM DSP6 Processor */
            EM_8051          Machine = 165 /* Intel 8051 and variants */
            EM_STXP7X        Machine = 166 /* STMicroelectronics STxP7x family of configurable and extensible RISC processors */
            EM_NDS32         Machine = 167 /* Andes Technology compact code size embedded RISC processor family */
            EM_ECOG1         Machine = 168 /* Cyan Technology eCOG1X family */
            EM_ECOG1X        Machine = 168 /* Cyan Technology eCOG1X family */
            EM_MAXQ30        Machine = 169 /* Dallas Semiconductor MAXQ30 Core Micro-controllers */
            EM_XIMO16        Machine = 170 /* New Japan Radio (NJR) 16-bit DSP Processor */
            EM_MANIK         Machine = 171 /* M2000 Reconfigurable RISC Microprocessor */
            EM_CRAYNV2       Machine = 172 /* Cray Inc. NV2 vector architecture */
            EM_RX            Machine = 173 /* Renesas RX family */
            EM_METAG         Machine = 174 /* Imagination Technologies META processor architecture */
            EM_MCST_ELBRUS   Machine = 175 /* MCST Elbrus general purpose hardware architecture */
            EM_ECOG16        Machine = 176 /* Cyan Technology eCOG16 family */
            EM_CR16          Machine = 177 /* National Semiconductor CompactRISC CR16 16-bit microprocessor */
            EM_ETPU          Machine = 178 /* Freescale Extended Time Processing Unit */
            EM_SLE9X         Machine = 179 /* Infineon Technologies SLE9X core */
            EM_L10M          Machine = 180 /* Intel L10M */
            EM_K10M          Machine = 181 /* Intel K10M */
            EM_AARCH64       Machine = 183 /* ARM 64-bit Architecture (AArch64) */
            EM_AVR32         Machine = 185 /* Atmel Corporation 32-bit microprocessor family */
            EM_STM8          Machine = 186 /* STMicroeletronics STM8 8-bit microcontroller */
            EM_TILE64        Machine = 187 /* Tilera TILE64 multicore architecture family */
            EM_TILEPRO       Machine = 188 /* Tilera TILEPro multicore architecture family */
            EM_MICROBLAZE    Machine = 189 /* Xilinx MicroBlaze 32-bit RISC soft processor core */
            EM_CUDA          Machine = 190 /* NVIDIA CUDA architecture */
            EM_TILEGX        Machine = 191 /* Tilera TILE-Gx multicore architecture family */
            EM_CLOUDSHIELD   Machine = 192 /* CloudShield architecture family */
            EM_COREA_1ST     Machine = 193 /* KIPO-KAIST Core-A 1st generation processor family */
            EM_COREA_2ND     Machine = 194 /* KIPO-KAIST Core-A 2nd generation processor family */
            EM_ARC_COMPACT2  Machine = 195 /* Synopsys ARCompact V2 */
            EM_OPEN8         Machine = 196 /* Open8 8-bit RISC soft processor core */
            EM_RL78          Machine = 197 /* Renesas RL78 family */
            EM_VIDEOCORE5    Machine = 198 /* Broadcom VideoCore V processor */
            EM_78KOR         Machine = 199 /* Renesas 78KOR family */
            EM_56800EX       Machine = 200 /* Freescale 56800EX Digital Signal Controller (DSC) */
            EM_BA1           Machine = 201 /* Beyond BA1 CPU architecture */
            EM_BA2           Machine = 202 /* Beyond BA2 CPU architecture */
            EM_XCORE         Machine = 203 /* XMOS xCORE processor family */
            EM_MCHP_PIC      Machine = 204 /* Microchip 8-bit PIC(r) family */
            EM_INTEL205      Machine = 205 /* Reserved by Intel */
            EM_INTEL206      Machine = 206 /* Reserved by Intel */
            EM_INTEL207      Machine = 207 /* Reserved by Intel */
            EM_INTEL208      Machine = 208 /* Reserved by Intel */
            EM_INTEL209      Machine = 209 /* Reserved by Intel */
            EM_KM32          Machine = 210 /* KM211 KM32 32-bit processor */
            EM_KMX32         Machine = 211 /* KM211 KMX32 32-bit processor */
            EM_KMX16         Machine = 212 /* KM211 KMX16 16-bit processor */
            EM_KMX8          Machine = 213 /* KM211 KMX8 8-bit processor */
            EM_KVARC         Machine = 214 /* KM211 KVARC processor */
            EM_CDP           Machine = 215 /* Paneve CDP architecture family */
            EM_COGE          Machine = 216 /* Cognitive Smart Memory Processor */
            EM_COOL          Machine = 217 /* Bluechip Systems CoolEngine */
            EM_NORC          Machine = 218 /* Nanoradio Optimized RISC */
            EM_CSR_KALIMBA   Machine = 219 /* CSR Kalimba architecture family */
            EM_Z80           Machine = 220 /* Zilog Z80 */
            EM_VISIUM        Machine = 221 /* Controls and Data Services VISIUMcore processor */
            EM_FT32          Machine = 222 /* FTDI Chip FT32 high performance 32-bit RISC architecture */
            EM_MOXIE         Machine = 223 /* Moxie processor family */
            EM_AMDGPU        Machine = 224 /* AMD GPU architecture */
            EM_RISCV         Machine = 243 /* RISC-V */
            EM_LANAI         Machine = 244 /* Lanai 32-bit processor */
            EM_BPF           Machine = 247 /* Linux BPF – in-kernel virtual machine */
            EM_LOONGARCH     Machine = 258 /* LoongArch */
        
            /* Non-standard or deprecated. */
            EM_486         Machine = 6      /* Intel i486. */
            EM_MIPS_RS4_BE Machine = 10     /* MIPS R4000 Big-Endian */
            EM_ALPHA_STD   Machine = 41     /* Digital Alpha (standard value). */
            EM_ALPHA       Machine = 0x9026 /* Alpha (written in the absence of an ABI) */
        )

        func (Machine) GoString

        func (i Machine) GoString() string

        func (Machine) String

        func (i Machine) String() string

        type NType

        NType values; used in core files.

        type NType int
        const (
            NT_PRSTATUS NType = 1 /* Process status. */
            NT_FPREGSET NType = 2 /* Floating point registers. */
            NT_PRPSINFO NType = 3 /* Process state info. */
        )

        func (NType) GoString

        func (i NType) GoString() string

        func (NType) String

        func (i NType) String() string

        type OSABI

        OSABI is found in Header.Ident[EI_OSABI] and Header.OSABI.

        type OSABI byte
        const (
            ELFOSABI_NONE       OSABI = 0   /* UNIX System V ABI */
            ELFOSABI_HPUX       OSABI = 1   /* HP-UX operating system */
            ELFOSABI_NETBSD     OSABI = 2   /* NetBSD */
            ELFOSABI_LINUX      OSABI = 3   /* Linux */
            ELFOSABI_HURD       OSABI = 4   /* Hurd */
            ELFOSABI_86OPEN     OSABI = 5   /* 86Open common IA32 ABI */
            ELFOSABI_SOLARIS    OSABI = 6   /* Solaris */
            ELFOSABI_AIX        OSABI = 7   /* AIX */
            ELFOSABI_IRIX       OSABI = 8   /* IRIX */
            ELFOSABI_FREEBSD    OSABI = 9   /* FreeBSD */
            ELFOSABI_TRU64      OSABI = 10  /* TRU64 UNIX */
            ELFOSABI_MODESTO    OSABI = 11  /* Novell Modesto */
            ELFOSABI_OPENBSD    OSABI = 12  /* OpenBSD */
            ELFOSABI_OPENVMS    OSABI = 13  /* Open VMS */
            ELFOSABI_NSK        OSABI = 14  /* HP Non-Stop Kernel */
            ELFOSABI_AROS       OSABI = 15  /* Amiga Research OS */
            ELFOSABI_FENIXOS    OSABI = 16  /* The FenixOS highly scalable multi-core OS */
            ELFOSABI_CLOUDABI   OSABI = 17  /* Nuxi CloudABI */
            ELFOSABI_ARM        OSABI = 97  /* ARM */
            ELFOSABI_STANDALONE OSABI = 255 /* Standalone (embedded) application */
        )

        func (OSABI) GoString

        func (i OSABI) GoString() string

        func (OSABI) String

        func (i OSABI) String() string

        type Prog

        A Prog represents a single ELF program header in an ELF binary.

        type Prog struct {
            ProgHeader
        
            // Embed ReaderAt for ReadAt method.
            // Do not embed SectionReader directly
            // to avoid having Read and Seek.
            // If a client wants Read and Seek it must use
            // Open() to avoid fighting over the seek offset
            // with other clients.
            io.ReaderAt
            // contains filtered or unexported fields
        }
        

        func (*Prog) Open

        func (p *Prog) Open() io.ReadSeeker

        Open returns a new ReadSeeker reading the ELF program body.

        type Prog32

        ELF32 Program header.

        type Prog32 struct {
            Type   uint32 /* Entry type. */
            Off    uint32 /* File offset of contents. */
            Vaddr  uint32 /* Virtual address in memory image. */
            Paddr  uint32 /* Physical address (not used). */
            Filesz uint32 /* Size of contents in file. */
            Memsz  uint32 /* Size of contents in memory. */
            Flags  uint32 /* Access permission flags. */
            Align  uint32 /* Alignment in memory and file. */
        }
        

        type Prog64

        ELF64 Program header.

        type Prog64 struct {
            Type   uint32 /* Entry type. */
            Flags  uint32 /* Access permission flags. */
            Off    uint64 /* File offset of contents. */
            Vaddr  uint64 /* Virtual address in memory image. */
            Paddr  uint64 /* Physical address (not used). */
            Filesz uint64 /* Size of contents in file. */
            Memsz  uint64 /* Size of contents in memory. */
            Align  uint64 /* Alignment in memory and file. */
        }
        

        type ProgFlag

        Prog.Flag

        type ProgFlag uint32
        const (
            PF_X        ProgFlag = 0x1        /* Executable. */
            PF_W        ProgFlag = 0x2        /* Writable. */
            PF_R        ProgFlag = 0x4        /* Readable. */
            PF_MASKOS   ProgFlag = 0x0ff00000 /* Operating system-specific. */
            PF_MASKPROC ProgFlag = 0xf0000000 /* Processor-specific. */
        )

        func (ProgFlag) GoString

        func (i ProgFlag) GoString() string

        func (ProgFlag) String

        func (i ProgFlag) String() string

        type ProgHeader

        A ProgHeader represents a single ELF program header.

        type ProgHeader struct {
            Type   ProgType
            Flags  ProgFlag
            Off    uint64
            Vaddr  uint64
            Paddr  uint64
            Filesz uint64
            Memsz  uint64
            Align  uint64
        }
        

        type ProgType

        Prog.Type

        type ProgType int
        const (
            PT_NULL    ProgType = 0 /* Unused entry. */
            PT_LOAD    ProgType = 1 /* Loadable segment. */
            PT_DYNAMIC ProgType = 2 /* Dynamic linking information segment. */
            PT_INTERP  ProgType = 3 /* Pathname of interpreter. */
            PT_NOTE    ProgType = 4 /* Auxiliary information. */
            PT_SHLIB   ProgType = 5 /* Reserved (not used). */
            PT_PHDR    ProgType = 6 /* Location of program header itself. */
            PT_TLS     ProgType = 7 /* Thread local storage segment */
        
            PT_LOOS ProgType = 0x60000000 /* First OS-specific. */
        
            PT_GNU_EH_FRAME ProgType = 0x6474e550 /* Frame unwind information */
            PT_GNU_STACK    ProgType = 0x6474e551 /* Stack flags */
            PT_GNU_RELRO    ProgType = 0x6474e552 /* Read only after relocs */
            PT_GNU_PROPERTY ProgType = 0x6474e553 /* GNU property */
            PT_GNU_MBIND_LO ProgType = 0x6474e555 /* Mbind segments start */
            PT_GNU_MBIND_HI ProgType = 0x6474f554 /* Mbind segments finish */
        
            PT_PAX_FLAGS ProgType = 0x65041580 /* PAX flags */
        
            PT_OPENBSD_RANDOMIZE ProgType = 0x65a3dbe6 /* Random data */
            PT_OPENBSD_WXNEEDED  ProgType = 0x65a3dbe7 /* W^X violations */
            PT_OPENBSD_BOOTDATA  ProgType = 0x65a41be6 /* Boot arguments */
        
            PT_SUNW_EH_FRAME ProgType = 0x6474e550 /* Frame unwind information */
            PT_SUNWSTACK     ProgType = 0x6ffffffb /* Stack segment */
        
            PT_HIOS ProgType = 0x6fffffff /* Last OS-specific. */
        
            PT_LOPROC ProgType = 0x70000000 /* First processor-specific type. */
        
            PT_ARM_ARCHEXT ProgType = 0x70000000 /* Architecture compatibility */
            PT_ARM_EXIDX   ProgType = 0x70000001 /* Exception unwind tables */
        
            PT_AARCH64_ARCHEXT ProgType = 0x70000000 /* Architecture compatibility */
            PT_AARCH64_UNWIND  ProgType = 0x70000001 /* Exception unwind tables */
        
            PT_MIPS_REGINFO  ProgType = 0x70000000 /* Register usage */
            PT_MIPS_RTPROC   ProgType = 0x70000001 /* Runtime procedures */
            PT_MIPS_OPTIONS  ProgType = 0x70000002 /* Options */
            PT_MIPS_ABIFLAGS ProgType = 0x70000003 /* ABI flags */
        
            PT_S390_PGSTE ProgType = 0x70000000 /* 4k page table size */
        
            PT_HIPROC ProgType = 0x7fffffff /* Last processor-specific type. */
        )

        func (ProgType) GoString

        func (i ProgType) GoString() string

        func (ProgType) String

        func (i ProgType) String() string

        type R_386

        Relocation types for 386.

        type R_386 int
        const (
            R_386_NONE          R_386 = 0  /* No relocation. */
            R_386_32            R_386 = 1  /* Add symbol value. */
            R_386_PC32          R_386 = 2  /* Add PC-relative symbol value. */
            R_386_GOT32         R_386 = 3  /* Add PC-relative GOT offset. */
            R_386_PLT32         R_386 = 4  /* Add PC-relative PLT offset. */
            R_386_COPY          R_386 = 5  /* Copy data from shared object. */
            R_386_GLOB_DAT      R_386 = 6  /* Set GOT entry to data address. */
            R_386_JMP_SLOT      R_386 = 7  /* Set GOT entry to code address. */
            R_386_RELATIVE      R_386 = 8  /* Add load address of shared object. */
            R_386_GOTOFF        R_386 = 9  /* Add GOT-relative symbol address. */
            R_386_GOTPC         R_386 = 10 /* Add PC-relative GOT table address. */
            R_386_32PLT         R_386 = 11
            R_386_TLS_TPOFF     R_386 = 14 /* Negative offset in static TLS block */
            R_386_TLS_IE        R_386 = 15 /* Absolute address of GOT for -ve static TLS */
            R_386_TLS_GOTIE     R_386 = 16 /* GOT entry for negative static TLS block */
            R_386_TLS_LE        R_386 = 17 /* Negative offset relative to static TLS */
            R_386_TLS_GD        R_386 = 18 /* 32 bit offset to GOT (index,off) pair */
            R_386_TLS_LDM       R_386 = 19 /* 32 bit offset to GOT (index,zero) pair */
            R_386_16            R_386 = 20
            R_386_PC16          R_386 = 21
            R_386_8             R_386 = 22
            R_386_PC8           R_386 = 23
            R_386_TLS_GD_32     R_386 = 24 /* 32 bit offset to GOT (index,off) pair */
            R_386_TLS_GD_PUSH   R_386 = 25 /* pushl instruction for Sun ABI GD sequence */
            R_386_TLS_GD_CALL   R_386 = 26 /* call instruction for Sun ABI GD sequence */
            R_386_TLS_GD_POP    R_386 = 27 /* popl instruction for Sun ABI GD sequence */
            R_386_TLS_LDM_32    R_386 = 28 /* 32 bit offset to GOT (index,zero) pair */
            R_386_TLS_LDM_PUSH  R_386 = 29 /* pushl instruction for Sun ABI LD sequence */
            R_386_TLS_LDM_CALL  R_386 = 30 /* call instruction for Sun ABI LD sequence */
            R_386_TLS_LDM_POP   R_386 = 31 /* popl instruction for Sun ABI LD sequence */
            R_386_TLS_LDO_32    R_386 = 32 /* 32 bit offset from start of TLS block */
            R_386_TLS_IE_32     R_386 = 33 /* 32 bit offset to GOT static TLS offset entry */
            R_386_TLS_LE_32     R_386 = 34 /* 32 bit offset within static TLS block */
            R_386_TLS_DTPMOD32  R_386 = 35 /* GOT entry containing TLS index */
            R_386_TLS_DTPOFF32  R_386 = 36 /* GOT entry containing TLS offset */
            R_386_TLS_TPOFF32   R_386 = 37 /* GOT entry of -ve static TLS offset */
            R_386_SIZE32        R_386 = 38
            R_386_TLS_GOTDESC   R_386 = 39
            R_386_TLS_DESC_CALL R_386 = 40
            R_386_TLS_DESC      R_386 = 41
            R_386_IRELATIVE     R_386 = 42
            R_386_GOT32X        R_386 = 43
        )

        func (R_386) GoString

        func (i R_386) GoString() string

        func (R_386) String

        func (i R_386) String() string

        type R_390

        Relocation types for s390x processors.

        type R_390 int
        const (
            R_390_NONE        R_390 = 0
            R_390_8           R_390 = 1
            R_390_12          R_390 = 2
            R_390_16          R_390 = 3
            R_390_32          R_390 = 4
            R_390_PC32        R_390 = 5
            R_390_GOT12       R_390 = 6
            R_390_GOT32       R_390 = 7
            R_390_PLT32       R_390 = 8
            R_390_COPY        R_390 = 9
            R_390_GLOB_DAT    R_390 = 10
            R_390_JMP_SLOT    R_390 = 11
            R_390_RELATIVE    R_390 = 12
            R_390_GOTOFF      R_390 = 13
            R_390_GOTPC       R_390 = 14
            R_390_GOT16       R_390 = 15
            R_390_PC16        R_390 = 16
            R_390_PC16DBL     R_390 = 17
            R_390_PLT16DBL    R_390 = 18
            R_390_PC32DBL     R_390 = 19
            R_390_PLT32DBL    R_390 = 20
            R_390_GOTPCDBL    R_390 = 21
            R_390_64          R_390 = 22
            R_390_PC64        R_390 = 23
            R_390_GOT64       R_390 = 24
            R_390_PLT64       R_390 = 25
            R_390_GOTENT      R_390 = 26
            R_390_GOTOFF16    R_390 = 27
            R_390_GOTOFF64    R_390 = 28
            R_390_GOTPLT12    R_390 = 29
            R_390_GOTPLT16    R_390 = 30
            R_390_GOTPLT32    R_390 = 31
            R_390_GOTPLT64    R_390 = 32
            R_390_GOTPLTENT   R_390 = 33
            R_390_GOTPLTOFF16 R_390 = 34
            R_390_GOTPLTOFF32 R_390 = 35
            R_390_GOTPLTOFF64 R_390 = 36
            R_390_TLS_LOAD    R_390 = 37
            R_390_TLS_GDCALL  R_390 = 38
            R_390_TLS_LDCALL  R_390 = 39
            R_390_TLS_GD32    R_390 = 40
            R_390_TLS_GD64    R_390 = 41
            R_390_TLS_GOTIE12 R_390 = 42
            R_390_TLS_GOTIE32 R_390 = 43
            R_390_TLS_GOTIE64 R_390 = 44
            R_390_TLS_LDM32   R_390 = 45
            R_390_TLS_LDM64   R_390 = 46
            R_390_TLS_IE32    R_390 = 47
            R_390_TLS_IE64    R_390 = 48
            R_390_TLS_IEENT   R_390 = 49
            R_390_TLS_LE32    R_390 = 50
            R_390_TLS_LE64    R_390 = 51
            R_390_TLS_LDO32   R_390 = 52
            R_390_TLS_LDO64   R_390 = 53
            R_390_TLS_DTPMOD  R_390 = 54
            R_390_TLS_DTPOFF  R_390 = 55
            R_390_TLS_TPOFF   R_390 = 56
            R_390_20          R_390 = 57
            R_390_GOT20       R_390 = 58
            R_390_GOTPLT20    R_390 = 59
            R_390_TLS_GOTIE20 R_390 = 60
        )

        func (R_390) GoString

        func (i R_390) GoString() string

        func (R_390) String

        func (i R_390) String() string

        type R_AARCH64

        Relocation types for AArch64 (aka arm64)

        type R_AARCH64 int
        const (
            R_AARCH64_NONE                            R_AARCH64 = 0
            R_AARCH64_P32_ABS32                       R_AARCH64 = 1
            R_AARCH64_P32_ABS16                       R_AARCH64 = 2
            R_AARCH64_P32_PREL32                      R_AARCH64 = 3
            R_AARCH64_P32_PREL16                      R_AARCH64 = 4
            R_AARCH64_P32_MOVW_UABS_G0                R_AARCH64 = 5
            R_AARCH64_P32_MOVW_UABS_G0_NC             R_AARCH64 = 6
            R_AARCH64_P32_MOVW_UABS_G1                R_AARCH64 = 7
            R_AARCH64_P32_MOVW_SABS_G0                R_AARCH64 = 8
            R_AARCH64_P32_LD_PREL_LO19                R_AARCH64 = 9
            R_AARCH64_P32_ADR_PREL_LO21               R_AARCH64 = 10
            R_AARCH64_P32_ADR_PREL_PG_HI21            R_AARCH64 = 11
            R_AARCH64_P32_ADD_ABS_LO12_NC             R_AARCH64 = 12
            R_AARCH64_P32_LDST8_ABS_LO12_NC           R_AARCH64 = 13
            R_AARCH64_P32_LDST16_ABS_LO12_NC          R_AARCH64 = 14
            R_AARCH64_P32_LDST32_ABS_LO12_NC          R_AARCH64 = 15
            R_AARCH64_P32_LDST64_ABS_LO12_NC          R_AARCH64 = 16
            R_AARCH64_P32_LDST128_ABS_LO12_NC         R_AARCH64 = 17
            R_AARCH64_P32_TSTBR14                     R_AARCH64 = 18
            R_AARCH64_P32_CONDBR19                    R_AARCH64 = 19
            R_AARCH64_P32_JUMP26                      R_AARCH64 = 20
            R_AARCH64_P32_CALL26                      R_AARCH64 = 21
            R_AARCH64_P32_GOT_LD_PREL19               R_AARCH64 = 25
            R_AARCH64_P32_ADR_GOT_PAGE                R_AARCH64 = 26
            R_AARCH64_P32_LD32_GOT_LO12_NC            R_AARCH64 = 27
            R_AARCH64_P32_TLSGD_ADR_PAGE21            R_AARCH64 = 81
            R_AARCH64_P32_TLSGD_ADD_LO12_NC           R_AARCH64 = 82
            R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21   R_AARCH64 = 103
            R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC R_AARCH64 = 104
            R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19    R_AARCH64 = 105
            R_AARCH64_P32_TLSLE_MOVW_TPREL_G1         R_AARCH64 = 106
            R_AARCH64_P32_TLSLE_MOVW_TPREL_G0         R_AARCH64 = 107
            R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC      R_AARCH64 = 108
            R_AARCH64_P32_TLSLE_ADD_TPREL_HI12        R_AARCH64 = 109
            R_AARCH64_P32_TLSLE_ADD_TPREL_LO12        R_AARCH64 = 110
            R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC     R_AARCH64 = 111
            R_AARCH64_P32_TLSDESC_LD_PREL19           R_AARCH64 = 122
            R_AARCH64_P32_TLSDESC_ADR_PREL21          R_AARCH64 = 123
            R_AARCH64_P32_TLSDESC_ADR_PAGE21          R_AARCH64 = 124
            R_AARCH64_P32_TLSDESC_LD32_LO12_NC        R_AARCH64 = 125
            R_AARCH64_P32_TLSDESC_ADD_LO12_NC         R_AARCH64 = 126
            R_AARCH64_P32_TLSDESC_CALL                R_AARCH64 = 127
            R_AARCH64_P32_COPY                        R_AARCH64 = 180
            R_AARCH64_P32_GLOB_DAT                    R_AARCH64 = 181
            R_AARCH64_P32_JUMP_SLOT                   R_AARCH64 = 182
            R_AARCH64_P32_RELATIVE                    R_AARCH64 = 183
            R_AARCH64_P32_TLS_DTPMOD                  R_AARCH64 = 184
            R_AARCH64_P32_TLS_DTPREL                  R_AARCH64 = 185
            R_AARCH64_P32_TLS_TPREL                   R_AARCH64 = 186
            R_AARCH64_P32_TLSDESC                     R_AARCH64 = 187
            R_AARCH64_P32_IRELATIVE                   R_AARCH64 = 188
            R_AARCH64_NULL                            R_AARCH64 = 256
            R_AARCH64_ABS64                           R_AARCH64 = 257
            R_AARCH64_ABS32                           R_AARCH64 = 258
            R_AARCH64_ABS16                           R_AARCH64 = 259
            R_AARCH64_PREL64                          R_AARCH64 = 260
            R_AARCH64_PREL32                          R_AARCH64 = 261
            R_AARCH64_PREL16                          R_AARCH64 = 262
            R_AARCH64_MOVW_UABS_G0                    R_AARCH64 = 263
            R_AARCH64_MOVW_UABS_G0_NC                 R_AARCH64 = 264
            R_AARCH64_MOVW_UABS_G1                    R_AARCH64 = 265
            R_AARCH64_MOVW_UABS_G1_NC                 R_AARCH64 = 266
            R_AARCH64_MOVW_UABS_G2                    R_AARCH64 = 267
            R_AARCH64_MOVW_UABS_G2_NC                 R_AARCH64 = 268
            R_AARCH64_MOVW_UABS_G3                    R_AARCH64 = 269
            R_AARCH64_MOVW_SABS_G0                    R_AARCH64 = 270
            R_AARCH64_MOVW_SABS_G1                    R_AARCH64 = 271
            R_AARCH64_MOVW_SABS_G2                    R_AARCH64 = 272
            R_AARCH64_LD_PREL_LO19                    R_AARCH64 = 273
            R_AARCH64_ADR_PREL_LO21                   R_AARCH64 = 274
            R_AARCH64_ADR_PREL_PG_HI21                R_AARCH64 = 275
            R_AARCH64_ADR_PREL_PG_HI21_NC             R_AARCH64 = 276
            R_AARCH64_ADD_ABS_LO12_NC                 R_AARCH64 = 277
            R_AARCH64_LDST8_ABS_LO12_NC               R_AARCH64 = 278
            R_AARCH64_TSTBR14                         R_AARCH64 = 279
            R_AARCH64_CONDBR19                        R_AARCH64 = 280
            R_AARCH64_JUMP26                          R_AARCH64 = 282
            R_AARCH64_CALL26                          R_AARCH64 = 283
            R_AARCH64_LDST16_ABS_LO12_NC              R_AARCH64 = 284
            R_AARCH64_LDST32_ABS_LO12_NC              R_AARCH64 = 285
            R_AARCH64_LDST64_ABS_LO12_NC              R_AARCH64 = 286
            R_AARCH64_LDST128_ABS_LO12_NC             R_AARCH64 = 299
            R_AARCH64_GOT_LD_PREL19                   R_AARCH64 = 309
            R_AARCH64_LD64_GOTOFF_LO15                R_AARCH64 = 310
            R_AARCH64_ADR_GOT_PAGE                    R_AARCH64 = 311
            R_AARCH64_LD64_GOT_LO12_NC                R_AARCH64 = 312
            R_AARCH64_LD64_GOTPAGE_LO15               R_AARCH64 = 313
            R_AARCH64_TLSGD_ADR_PREL21                R_AARCH64 = 512
            R_AARCH64_TLSGD_ADR_PAGE21                R_AARCH64 = 513
            R_AARCH64_TLSGD_ADD_LO12_NC               R_AARCH64 = 514
            R_AARCH64_TLSGD_MOVW_G1                   R_AARCH64 = 515
            R_AARCH64_TLSGD_MOVW_G0_NC                R_AARCH64 = 516
            R_AARCH64_TLSLD_ADR_PREL21                R_AARCH64 = 517
            R_AARCH64_TLSLD_ADR_PAGE21                R_AARCH64 = 518
            R_AARCH64_TLSIE_MOVW_GOTTPREL_G1          R_AARCH64 = 539
            R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC       R_AARCH64 = 540
            R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21       R_AARCH64 = 541
            R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC     R_AARCH64 = 542
            R_AARCH64_TLSIE_LD_GOTTPREL_PREL19        R_AARCH64 = 543
            R_AARCH64_TLSLE_MOVW_TPREL_G2             R_AARCH64 = 544
            R_AARCH64_TLSLE_MOVW_TPREL_G1             R_AARCH64 = 545
            R_AARCH64_TLSLE_MOVW_TPREL_G1_NC          R_AARCH64 = 546
            R_AARCH64_TLSLE_MOVW_TPREL_G0             R_AARCH64 = 547
            R_AARCH64_TLSLE_MOVW_TPREL_G0_NC          R_AARCH64 = 548
            R_AARCH64_TLSLE_ADD_TPREL_HI12            R_AARCH64 = 549
            R_AARCH64_TLSLE_ADD_TPREL_LO12            R_AARCH64 = 550
            R_AARCH64_TLSLE_ADD_TPREL_LO12_NC         R_AARCH64 = 551
            R_AARCH64_TLSDESC_LD_PREL19               R_AARCH64 = 560
            R_AARCH64_TLSDESC_ADR_PREL21              R_AARCH64 = 561
            R_AARCH64_TLSDESC_ADR_PAGE21              R_AARCH64 = 562
            R_AARCH64_TLSDESC_LD64_LO12_NC            R_AARCH64 = 563
            R_AARCH64_TLSDESC_ADD_LO12_NC             R_AARCH64 = 564
            R_AARCH64_TLSDESC_OFF_G1                  R_AARCH64 = 565
            R_AARCH64_TLSDESC_OFF_G0_NC               R_AARCH64 = 566
            R_AARCH64_TLSDESC_LDR                     R_AARCH64 = 567
            R_AARCH64_TLSDESC_ADD                     R_AARCH64 = 568
            R_AARCH64_TLSDESC_CALL                    R_AARCH64 = 569
            R_AARCH64_TLSLE_LDST128_TPREL_LO12        R_AARCH64 = 570
            R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC     R_AARCH64 = 571
            R_AARCH64_TLSLD_LDST128_DTPREL_LO12       R_AARCH64 = 572
            R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC    R_AARCH64 = 573
            R_AARCH64_COPY                            R_AARCH64 = 1024
            R_AARCH64_GLOB_DAT                        R_AARCH64 = 1025
            R_AARCH64_JUMP_SLOT                       R_AARCH64 = 1026
            R_AARCH64_RELATIVE                        R_AARCH64 = 1027
            R_AARCH64_TLS_DTPMOD64                    R_AARCH64 = 1028
            R_AARCH64_TLS_DTPREL64                    R_AARCH64 = 1029
            R_AARCH64_TLS_TPREL64                     R_AARCH64 = 1030
            R_AARCH64_TLSDESC                         R_AARCH64 = 1031
            R_AARCH64_IRELATIVE                       R_AARCH64 = 1032
        )

        func (R_AARCH64) GoString

        func (i R_AARCH64) GoString() string

        func (R_AARCH64) String

        func (i R_AARCH64) String() string

        type R_ALPHA

        Relocation types for Alpha.

        type R_ALPHA int
        const (
            R_ALPHA_NONE           R_ALPHA = 0  /* No reloc */
            R_ALPHA_REFLONG        R_ALPHA = 1  /* Direct 32 bit */
            R_ALPHA_REFQUAD        R_ALPHA = 2  /* Direct 64 bit */
            R_ALPHA_GPREL32        R_ALPHA = 3  /* GP relative 32 bit */
            R_ALPHA_LITERAL        R_ALPHA = 4  /* GP relative 16 bit w/optimization */
            R_ALPHA_LITUSE         R_ALPHA = 5  /* Optimization hint for LITERAL */
            R_ALPHA_GPDISP         R_ALPHA = 6  /* Add displacement to GP */
            R_ALPHA_BRADDR         R_ALPHA = 7  /* PC+4 relative 23 bit shifted */
            R_ALPHA_HINT           R_ALPHA = 8  /* PC+4 relative 16 bit shifted */
            R_ALPHA_SREL16         R_ALPHA = 9  /* PC relative 16 bit */
            R_ALPHA_SREL32         R_ALPHA = 10 /* PC relative 32 bit */
            R_ALPHA_SREL64         R_ALPHA = 11 /* PC relative 64 bit */
            R_ALPHA_OP_PUSH        R_ALPHA = 12 /* OP stack push */
            R_ALPHA_OP_STORE       R_ALPHA = 13 /* OP stack pop and store */
            R_ALPHA_OP_PSUB        R_ALPHA = 14 /* OP stack subtract */
            R_ALPHA_OP_PRSHIFT     R_ALPHA = 15 /* OP stack right shift */
            R_ALPHA_GPVALUE        R_ALPHA = 16
            R_ALPHA_GPRELHIGH      R_ALPHA = 17
            R_ALPHA_GPRELLOW       R_ALPHA = 18
            R_ALPHA_IMMED_GP_16    R_ALPHA = 19
            R_ALPHA_IMMED_GP_HI32  R_ALPHA = 20
            R_ALPHA_IMMED_SCN_HI32 R_ALPHA = 21
            R_ALPHA_IMMED_BR_HI32  R_ALPHA = 22
            R_ALPHA_IMMED_LO32     R_ALPHA = 23
            R_ALPHA_COPY           R_ALPHA = 24 /* Copy symbol at runtime */
            R_ALPHA_GLOB_DAT       R_ALPHA = 25 /* Create GOT entry */
            R_ALPHA_JMP_SLOT       R_ALPHA = 26 /* Create PLT entry */
            R_ALPHA_RELATIVE       R_ALPHA = 27 /* Adjust by program base */
        )

        func (R_ALPHA) GoString

        func (i R_ALPHA) GoString() string

        func (R_ALPHA) String

        func (i R_ALPHA) String() string

        type R_ARM

        Relocation types for ARM.

        type R_ARM int
        const (
            R_ARM_NONE               R_ARM = 0 /* No relocation. */
            R_ARM_PC24               R_ARM = 1
            R_ARM_ABS32              R_ARM = 2
            R_ARM_REL32              R_ARM = 3
            R_ARM_PC13               R_ARM = 4
            R_ARM_ABS16              R_ARM = 5
            R_ARM_ABS12              R_ARM = 6
            R_ARM_THM_ABS5           R_ARM = 7
            R_ARM_ABS8               R_ARM = 8
            R_ARM_SBREL32            R_ARM = 9
            R_ARM_THM_PC22           R_ARM = 10
            R_ARM_THM_PC8            R_ARM = 11
            R_ARM_AMP_VCALL9         R_ARM = 12
            R_ARM_SWI24              R_ARM = 13
            R_ARM_THM_SWI8           R_ARM = 14
            R_ARM_XPC25              R_ARM = 15
            R_ARM_THM_XPC22          R_ARM = 16
            R_ARM_TLS_DTPMOD32       R_ARM = 17
            R_ARM_TLS_DTPOFF32       R_ARM = 18
            R_ARM_TLS_TPOFF32        R_ARM = 19
            R_ARM_COPY               R_ARM = 20 /* Copy data from shared object. */
            R_ARM_GLOB_DAT           R_ARM = 21 /* Set GOT entry to data address. */
            R_ARM_JUMP_SLOT          R_ARM = 22 /* Set GOT entry to code address. */
            R_ARM_RELATIVE           R_ARM = 23 /* Add load address of shared object. */
            R_ARM_GOTOFF             R_ARM = 24 /* Add GOT-relative symbol address. */
            R_ARM_GOTPC              R_ARM = 25 /* Add PC-relative GOT table address. */
            R_ARM_GOT32              R_ARM = 26 /* Add PC-relative GOT offset. */
            R_ARM_PLT32              R_ARM = 27 /* Add PC-relative PLT offset. */
            R_ARM_CALL               R_ARM = 28
            R_ARM_JUMP24             R_ARM = 29
            R_ARM_THM_JUMP24         R_ARM = 30
            R_ARM_BASE_ABS           R_ARM = 31
            R_ARM_ALU_PCREL_7_0      R_ARM = 32
            R_ARM_ALU_PCREL_15_8     R_ARM = 33
            R_ARM_ALU_PCREL_23_15    R_ARM = 34
            R_ARM_LDR_SBREL_11_10_NC R_ARM = 35
            R_ARM_ALU_SBREL_19_12_NC R_ARM = 36
            R_ARM_ALU_SBREL_27_20_CK R_ARM = 37
            R_ARM_TARGET1            R_ARM = 38
            R_ARM_SBREL31            R_ARM = 39
            R_ARM_V4BX               R_ARM = 40
            R_ARM_TARGET2            R_ARM = 41
            R_ARM_PREL31             R_ARM = 42
            R_ARM_MOVW_ABS_NC        R_ARM = 43
            R_ARM_MOVT_ABS           R_ARM = 44
            R_ARM_MOVW_PREL_NC       R_ARM = 45
            R_ARM_MOVT_PREL          R_ARM = 46
            R_ARM_THM_MOVW_ABS_NC    R_ARM = 47
            R_ARM_THM_MOVT_ABS       R_ARM = 48
            R_ARM_THM_MOVW_PREL_NC   R_ARM = 49
            R_ARM_THM_MOVT_PREL      R_ARM = 50
            R_ARM_THM_JUMP19         R_ARM = 51
            R_ARM_THM_JUMP6          R_ARM = 52
            R_ARM_THM_ALU_PREL_11_0  R_ARM = 53
            R_ARM_THM_PC12           R_ARM = 54
            R_ARM_ABS32_NOI          R_ARM = 55
            R_ARM_REL32_NOI          R_ARM = 56
            R_ARM_ALU_PC_G0_NC       R_ARM = 57
            R_ARM_ALU_PC_G0          R_ARM = 58
            R_ARM_ALU_PC_G1_NC       R_ARM = 59
            R_ARM_ALU_PC_G1          R_ARM = 60
            R_ARM_ALU_PC_G2          R_ARM = 61
            R_ARM_LDR_PC_G1          R_ARM = 62
            R_ARM_LDR_PC_G2          R_ARM = 63
            R_ARM_LDRS_PC_G0         R_ARM = 64
            R_ARM_LDRS_PC_G1         R_ARM = 65
            R_ARM_LDRS_PC_G2         R_ARM = 66
            R_ARM_LDC_PC_G0          R_ARM = 67
            R_ARM_LDC_PC_G1          R_ARM = 68
            R_ARM_LDC_PC_G2          R_ARM = 69
            R_ARM_ALU_SB_G0_NC       R_ARM = 70
            R_ARM_ALU_SB_G0          R_ARM = 71
            R_ARM_ALU_SB_G1_NC       R_ARM = 72
            R_ARM_ALU_SB_G1          R_ARM = 73
            R_ARM_ALU_SB_G2          R_ARM = 74
            R_ARM_LDR_SB_G0          R_ARM = 75
            R_ARM_LDR_SB_G1          R_ARM = 76
            R_ARM_LDR_SB_G2          R_ARM = 77
            R_ARM_LDRS_SB_G0         R_ARM = 78
            R_ARM_LDRS_SB_G1         R_ARM = 79
            R_ARM_LDRS_SB_G2         R_ARM = 80
            R_ARM_LDC_SB_G0          R_ARM = 81
            R_ARM_LDC_SB_G1          R_ARM = 82
            R_ARM_LDC_SB_G2          R_ARM = 83
            R_ARM_MOVW_BREL_NC       R_ARM = 84
            R_ARM_MOVT_BREL          R_ARM = 85
            R_ARM_MOVW_BREL          R_ARM = 86
            R_ARM_THM_MOVW_BREL_NC   R_ARM = 87
            R_ARM_THM_MOVT_BREL      R_ARM = 88
            R_ARM_THM_MOVW_BREL      R_ARM = 89
            R_ARM_TLS_GOTDESC        R_ARM = 90
            R_ARM_TLS_CALL           R_ARM = 91
            R_ARM_TLS_DESCSEQ        R_ARM = 92
            R_ARM_THM_TLS_CALL       R_ARM = 93
            R_ARM_PLT32_ABS          R_ARM = 94
            R_ARM_GOT_ABS            R_ARM = 95
            R_ARM_GOT_PREL           R_ARM = 96
            R_ARM_GOT_BREL12         R_ARM = 97
            R_ARM_GOTOFF12           R_ARM = 98
            R_ARM_GOTRELAX           R_ARM = 99
            R_ARM_GNU_VTENTRY        R_ARM = 100
            R_ARM_GNU_VTINHERIT      R_ARM = 101
            R_ARM_THM_JUMP11         R_ARM = 102
            R_ARM_THM_JUMP8          R_ARM = 103
            R_ARM_TLS_GD32           R_ARM = 104
            R_ARM_TLS_LDM32          R_ARM = 105
            R_ARM_TLS_LDO32          R_ARM = 106
            R_ARM_TLS_IE32           R_ARM = 107
            R_ARM_TLS_LE32           R_ARM = 108
            R_ARM_TLS_LDO12          R_ARM = 109
            R_ARM_TLS_LE12           R_ARM = 110
            R_ARM_TLS_IE12GP         R_ARM = 111
            R_ARM_PRIVATE_0          R_ARM = 112
            R_ARM_PRIVATE_1          R_ARM = 113
            R_ARM_PRIVATE_2          R_ARM = 114
            R_ARM_PRIVATE_3          R_ARM = 115
            R_ARM_PRIVATE_4          R_ARM = 116
            R_ARM_PRIVATE_5          R_ARM = 117
            R_ARM_PRIVATE_6          R_ARM = 118
            R_ARM_PRIVATE_7          R_ARM = 119
            R_ARM_PRIVATE_8          R_ARM = 120
            R_ARM_PRIVATE_9          R_ARM = 121
            R_ARM_PRIVATE_10         R_ARM = 122
            R_ARM_PRIVATE_11         R_ARM = 123
            R_ARM_PRIVATE_12         R_ARM = 124
            R_ARM_PRIVATE_13         R_ARM = 125
            R_ARM_PRIVATE_14         R_ARM = 126
            R_ARM_PRIVATE_15         R_ARM = 127
            R_ARM_ME_TOO             R_ARM = 128
            R_ARM_THM_TLS_DESCSEQ16  R_ARM = 129
            R_ARM_THM_TLS_DESCSEQ32  R_ARM = 130
            R_ARM_THM_GOT_BREL12     R_ARM = 131
            R_ARM_THM_ALU_ABS_G0_NC  R_ARM = 132
            R_ARM_THM_ALU_ABS_G1_NC  R_ARM = 133
            R_ARM_THM_ALU_ABS_G2_NC  R_ARM = 134
            R_ARM_THM_ALU_ABS_G3     R_ARM = 135
            R_ARM_IRELATIVE          R_ARM = 160
            R_ARM_RXPC25             R_ARM = 249
            R_ARM_RSBREL32           R_ARM = 250
            R_ARM_THM_RPC22          R_ARM = 251
            R_ARM_RREL32             R_ARM = 252
            R_ARM_RABS32             R_ARM = 253
            R_ARM_RPC24              R_ARM = 254
            R_ARM_RBASE              R_ARM = 255
        )

        func (R_ARM) GoString

        func (i R_ARM) GoString() string

        func (R_ARM) String

        func (i R_ARM) String() string

        type R_LARCH

        Relocation types for LoongArch.

        type R_LARCH int
        const (
            R_LARCH_NONE                       R_LARCH = 0
            R_LARCH_32                         R_LARCH = 1
            R_LARCH_64                         R_LARCH = 2
            R_LARCH_RELATIVE                   R_LARCH = 3
            R_LARCH_COPY                       R_LARCH = 4
            R_LARCH_JUMP_SLOT                  R_LARCH = 5
            R_LARCH_TLS_DTPMOD32               R_LARCH = 6
            R_LARCH_TLS_DTPMOD64               R_LARCH = 7
            R_LARCH_TLS_DTPREL32               R_LARCH = 8
            R_LARCH_TLS_DTPREL64               R_LARCH = 9
            R_LARCH_TLS_TPREL32                R_LARCH = 10
            R_LARCH_TLS_TPREL64                R_LARCH = 11
            R_LARCH_IRELATIVE                  R_LARCH = 12
            R_LARCH_MARK_LA                    R_LARCH = 20
            R_LARCH_MARK_PCREL                 R_LARCH = 21
            R_LARCH_SOP_PUSH_PCREL             R_LARCH = 22
            R_LARCH_SOP_PUSH_ABSOLUTE          R_LARCH = 23
            R_LARCH_SOP_PUSH_DUP               R_LARCH = 24
            R_LARCH_SOP_PUSH_GPREL             R_LARCH = 25
            R_LARCH_SOP_PUSH_TLS_TPREL         R_LARCH = 26
            R_LARCH_SOP_PUSH_TLS_GOT           R_LARCH = 27
            R_LARCH_SOP_PUSH_TLS_GD            R_LARCH = 28
            R_LARCH_SOP_PUSH_PLT_PCREL         R_LARCH = 29
            R_LARCH_SOP_ASSERT                 R_LARCH = 30
            R_LARCH_SOP_NOT                    R_LARCH = 31
            R_LARCH_SOP_SUB                    R_LARCH = 32
            R_LARCH_SOP_SL                     R_LARCH = 33
            R_LARCH_SOP_SR                     R_LARCH = 34
            R_LARCH_SOP_ADD                    R_LARCH = 35
            R_LARCH_SOP_AND                    R_LARCH = 36
            R_LARCH_SOP_IF_ELSE                R_LARCH = 37
            R_LARCH_SOP_POP_32_S_10_5          R_LARCH = 38
            R_LARCH_SOP_POP_32_U_10_12         R_LARCH = 39
            R_LARCH_SOP_POP_32_S_10_12         R_LARCH = 40
            R_LARCH_SOP_POP_32_S_10_16         R_LARCH = 41
            R_LARCH_SOP_POP_32_S_10_16_S2      R_LARCH = 42
            R_LARCH_SOP_POP_32_S_5_20          R_LARCH = 43
            R_LARCH_SOP_POP_32_S_0_5_10_16_S2  R_LARCH = 44
            R_LARCH_SOP_POP_32_S_0_10_10_16_S2 R_LARCH = 45
            R_LARCH_SOP_POP_32_U               R_LARCH = 46
            R_LARCH_ADD8                       R_LARCH = 47
            R_LARCH_ADD16                      R_LARCH = 48
            R_LARCH_ADD24                      R_LARCH = 49
            R_LARCH_ADD32                      R_LARCH = 50
            R_LARCH_ADD64                      R_LARCH = 51
            R_LARCH_SUB8                       R_LARCH = 52
            R_LARCH_SUB16                      R_LARCH = 53
            R_LARCH_SUB24                      R_LARCH = 54
            R_LARCH_SUB32                      R_LARCH = 55
            R_LARCH_SUB64                      R_LARCH = 56
            R_LARCH_GNU_VTINHERIT              R_LARCH = 57
            R_LARCH_GNU_VTENTRY                R_LARCH = 58
            R_LARCH_B16                        R_LARCH = 64
            R_LARCH_B21                        R_LARCH = 65
            R_LARCH_B26                        R_LARCH = 66
            R_LARCH_ABS_HI20                   R_LARCH = 67
            R_LARCH_ABS_LO12                   R_LARCH = 68
            R_LARCH_ABS64_LO20                 R_LARCH = 69
            R_LARCH_ABS64_HI12                 R_LARCH = 70
            R_LARCH_PCALA_HI20                 R_LARCH = 71
            R_LARCH_PCALA_LO12                 R_LARCH = 72
            R_LARCH_PCALA64_LO20               R_LARCH = 73
            R_LARCH_PCALA64_HI12               R_LARCH = 74
            R_LARCH_GOT_PC_HI20                R_LARCH = 75
            R_LARCH_GOT_PC_LO12                R_LARCH = 76
            R_LARCH_GOT64_PC_LO20              R_LARCH = 77
            R_LARCH_GOT64_PC_HI12              R_LARCH = 78
            R_LARCH_GOT_HI20                   R_LARCH = 79
            R_LARCH_GOT_LO12                   R_LARCH = 80
            R_LARCH_GOT64_LO20                 R_LARCH = 81
            R_LARCH_GOT64_HI12                 R_LARCH = 82
            R_LARCH_TLS_LE_HI20                R_LARCH = 83
            R_LARCH_TLS_LE_LO12                R_LARCH = 84
            R_LARCH_TLS_LE64_LO20              R_LARCH = 85
            R_LARCH_TLS_LE64_HI12              R_LARCH = 86
            R_LARCH_TLS_IE_PC_HI20             R_LARCH = 87
            R_LARCH_TLS_IE_PC_LO12             R_LARCH = 88
            R_LARCH_TLS_IE64_PC_LO20           R_LARCH = 89
            R_LARCH_TLS_IE64_PC_HI12           R_LARCH = 90
            R_LARCH_TLS_IE_HI20                R_LARCH = 91
            R_LARCH_TLS_IE_LO12                R_LARCH = 92
            R_LARCH_TLS_IE64_LO20              R_LARCH = 93
            R_LARCH_TLS_IE64_HI12              R_LARCH = 94
            R_LARCH_TLS_LD_PC_HI20             R_LARCH = 95
            R_LARCH_TLS_LD_HI20                R_LARCH = 96
            R_LARCH_TLS_GD_PC_HI20             R_LARCH = 97
            R_LARCH_TLS_GD_HI20                R_LARCH = 98
            R_LARCH_32_PCREL                   R_LARCH = 99
            R_LARCH_RELAX                      R_LARCH = 100
            R_LARCH_DELETE                     R_LARCH = 101
            R_LARCH_ALIGN                      R_LARCH = 102
            R_LARCH_PCREL20_S2                 R_LARCH = 103
            R_LARCH_CFA                        R_LARCH = 104
            R_LARCH_ADD6                       R_LARCH = 105
            R_LARCH_SUB6                       R_LARCH = 106
            R_LARCH_ADD_ULEB128                R_LARCH = 107
            R_LARCH_SUB_ULEB128                R_LARCH = 108
            R_LARCH_64_PCREL                   R_LARCH = 109
        )

        func (R_LARCH) GoString

        func (i R_LARCH) GoString() string

        func (R_LARCH) String

        func (i R_LARCH) String() string

        type R_MIPS

        Relocation types for MIPS.

        type R_MIPS int
        const (
            R_MIPS_NONE          R_MIPS = 0
            R_MIPS_16            R_MIPS = 1
            R_MIPS_32            R_MIPS = 2
            R_MIPS_REL32         R_MIPS = 3
            R_MIPS_26            R_MIPS = 4
            R_MIPS_HI16          R_MIPS = 5  /* high 16 bits of symbol value */
            R_MIPS_LO16          R_MIPS = 6  /* low 16 bits of symbol value */
            R_MIPS_GPREL16       R_MIPS = 7  /* GP-relative reference  */
            R_MIPS_LITERAL       R_MIPS = 8  /* Reference to literal section  */
            R_MIPS_GOT16         R_MIPS = 9  /* Reference to global offset table */
            R_MIPS_PC16          R_MIPS = 10 /* 16 bit PC relative reference */
            R_MIPS_CALL16        R_MIPS = 11 /* 16 bit call through glbl offset tbl */
            R_MIPS_GPREL32       R_MIPS = 12
            R_MIPS_SHIFT5        R_MIPS = 16
            R_MIPS_SHIFT6        R_MIPS = 17
            R_MIPS_64            R_MIPS = 18
            R_MIPS_GOT_DISP      R_MIPS = 19
            R_MIPS_GOT_PAGE      R_MIPS = 20
            R_MIPS_GOT_OFST      R_MIPS = 21
            R_MIPS_GOT_HI16      R_MIPS = 22
            R_MIPS_GOT_LO16      R_MIPS = 23
            R_MIPS_SUB           R_MIPS = 24
            R_MIPS_INSERT_A      R_MIPS = 25
            R_MIPS_INSERT_B      R_MIPS = 26
            R_MIPS_DELETE        R_MIPS = 27
            R_MIPS_HIGHER        R_MIPS = 28
            R_MIPS_HIGHEST       R_MIPS = 29
            R_MIPS_CALL_HI16     R_MIPS = 30
            R_MIPS_CALL_LO16     R_MIPS = 31
            R_MIPS_SCN_DISP      R_MIPS = 32
            R_MIPS_REL16         R_MIPS = 33
            R_MIPS_ADD_IMMEDIATE R_MIPS = 34
            R_MIPS_PJUMP         R_MIPS = 35
            R_MIPS_RELGOT        R_MIPS = 36
            R_MIPS_JALR          R_MIPS = 37
        
            R_MIPS_TLS_DTPMOD32    R_MIPS = 38 /* Module number 32 bit */
            R_MIPS_TLS_DTPREL32    R_MIPS = 39 /* Module-relative offset 32 bit */
            R_MIPS_TLS_DTPMOD64    R_MIPS = 40 /* Module number 64 bit */
            R_MIPS_TLS_DTPREL64    R_MIPS = 41 /* Module-relative offset 64 bit */
            R_MIPS_TLS_GD          R_MIPS = 42 /* 16 bit GOT offset for GD */
            R_MIPS_TLS_LDM         R_MIPS = 43 /* 16 bit GOT offset for LDM */
            R_MIPS_TLS_DTPREL_HI16 R_MIPS = 44 /* Module-relative offset, high 16 bits */
            R_MIPS_TLS_DTPREL_LO16 R_MIPS = 45 /* Module-relative offset, low 16 bits */
            R_MIPS_TLS_GOTTPREL    R_MIPS = 46 /* 16 bit GOT offset for IE */
            R_MIPS_TLS_TPREL32     R_MIPS = 47 /* TP-relative offset, 32 bit */
            R_MIPS_TLS_TPREL64     R_MIPS = 48 /* TP-relative offset, 64 bit */
            R_MIPS_TLS_TPREL_HI16  R_MIPS = 49 /* TP-relative offset, high 16 bits */
            R_MIPS_TLS_TPREL_LO16  R_MIPS = 50 /* TP-relative offset, low 16 bits */
        
            R_MIPS_PC32 R_MIPS = 248 /* 32 bit PC relative reference */
        )

        func (R_MIPS) GoString

        func (i R_MIPS) GoString() string

        func (R_MIPS) String

        func (i R_MIPS) String() string

        type R_PPC

        Relocation types for PowerPC.

        Values that are shared by both R_PPC and R_PPC64 are prefixed with R_POWERPC_ in the ELF standard. For the R_PPC type, the relevant shared relocations have been renamed with the prefix R_PPC_. The original name follows the value in a comment.

        type R_PPC int
        const (
            R_PPC_NONE            R_PPC = 0  // R_POWERPC_NONE
            R_PPC_ADDR32          R_PPC = 1  // R_POWERPC_ADDR32
            R_PPC_ADDR24          R_PPC = 2  // R_POWERPC_ADDR24
            R_PPC_ADDR16          R_PPC = 3  // R_POWERPC_ADDR16
            R_PPC_ADDR16_LO       R_PPC = 4  // R_POWERPC_ADDR16_LO
            R_PPC_ADDR16_HI       R_PPC = 5  // R_POWERPC_ADDR16_HI
            R_PPC_ADDR16_HA       R_PPC = 6  // R_POWERPC_ADDR16_HA
            R_PPC_ADDR14          R_PPC = 7  // R_POWERPC_ADDR14
            R_PPC_ADDR14_BRTAKEN  R_PPC = 8  // R_POWERPC_ADDR14_BRTAKEN
            R_PPC_ADDR14_BRNTAKEN R_PPC = 9  // R_POWERPC_ADDR14_BRNTAKEN
            R_PPC_REL24           R_PPC = 10 // R_POWERPC_REL24
            R_PPC_REL14           R_PPC = 11 // R_POWERPC_REL14
            R_PPC_REL14_BRTAKEN   R_PPC = 12 // R_POWERPC_REL14_BRTAKEN
            R_PPC_REL14_BRNTAKEN  R_PPC = 13 // R_POWERPC_REL14_BRNTAKEN
            R_PPC_GOT16           R_PPC = 14 // R_POWERPC_GOT16
            R_PPC_GOT16_LO        R_PPC = 15 // R_POWERPC_GOT16_LO
            R_PPC_GOT16_HI        R_PPC = 16 // R_POWERPC_GOT16_HI
            R_PPC_GOT16_HA        R_PPC = 17 // R_POWERPC_GOT16_HA
            R_PPC_PLTREL24        R_PPC = 18
            R_PPC_COPY            R_PPC = 19 // R_POWERPC_COPY
            R_PPC_GLOB_DAT        R_PPC = 20 // R_POWERPC_GLOB_DAT
            R_PPC_JMP_SLOT        R_PPC = 21 // R_POWERPC_JMP_SLOT
            R_PPC_RELATIVE        R_PPC = 22 // R_POWERPC_RELATIVE
            R_PPC_LOCAL24PC       R_PPC = 23
            R_PPC_UADDR32         R_PPC = 24 // R_POWERPC_UADDR32
            R_PPC_UADDR16         R_PPC = 25 // R_POWERPC_UADDR16
            R_PPC_REL32           R_PPC = 26 // R_POWERPC_REL32
            R_PPC_PLT32           R_PPC = 27 // R_POWERPC_PLT32
            R_PPC_PLTREL32        R_PPC = 28 // R_POWERPC_PLTREL32
            R_PPC_PLT16_LO        R_PPC = 29 // R_POWERPC_PLT16_LO
            R_PPC_PLT16_HI        R_PPC = 30 // R_POWERPC_PLT16_HI
            R_PPC_PLT16_HA        R_PPC = 31 // R_POWERPC_PLT16_HA
            R_PPC_SDAREL16        R_PPC = 32
            R_PPC_SECTOFF         R_PPC = 33 // R_POWERPC_SECTOFF
            R_PPC_SECTOFF_LO      R_PPC = 34 // R_POWERPC_SECTOFF_LO
            R_PPC_SECTOFF_HI      R_PPC = 35 // R_POWERPC_SECTOFF_HI
            R_PPC_SECTOFF_HA      R_PPC = 36 // R_POWERPC_SECTOFF_HA
            R_PPC_TLS             R_PPC = 67 // R_POWERPC_TLS
            R_PPC_DTPMOD32        R_PPC = 68 // R_POWERPC_DTPMOD32
            R_PPC_TPREL16         R_PPC = 69 // R_POWERPC_TPREL16
            R_PPC_TPREL16_LO      R_PPC = 70 // R_POWERPC_TPREL16_LO
            R_PPC_TPREL16_HI      R_PPC = 71 // R_POWERPC_TPREL16_HI
            R_PPC_TPREL16_HA      R_PPC = 72 // R_POWERPC_TPREL16_HA
            R_PPC_TPREL32         R_PPC = 73 // R_POWERPC_TPREL32
            R_PPC_DTPREL16        R_PPC = 74 // R_POWERPC_DTPREL16
            R_PPC_DTPREL16_LO     R_PPC = 75 // R_POWERPC_DTPREL16_LO
            R_PPC_DTPREL16_HI     R_PPC = 76 // R_POWERPC_DTPREL16_HI
            R_PPC_DTPREL16_HA     R_PPC = 77 // R_POWERPC_DTPREL16_HA
            R_PPC_DTPREL32        R_PPC = 78 // R_POWERPC_DTPREL32
            R_PPC_GOT_TLSGD16     R_PPC = 79 // R_POWERPC_GOT_TLSGD16
            R_PPC_GOT_TLSGD16_LO  R_PPC = 80 // R_POWERPC_GOT_TLSGD16_LO
            R_PPC_GOT_TLSGD16_HI  R_PPC = 81 // R_POWERPC_GOT_TLSGD16_HI
            R_PPC_GOT_TLSGD16_HA  R_PPC = 82 // R_POWERPC_GOT_TLSGD16_HA
            R_PPC_GOT_TLSLD16     R_PPC = 83 // R_POWERPC_GOT_TLSLD16
            R_PPC_GOT_TLSLD16_LO  R_PPC = 84 // R_POWERPC_GOT_TLSLD16_LO
            R_PPC_GOT_TLSLD16_HI  R_PPC = 85 // R_POWERPC_GOT_TLSLD16_HI
            R_PPC_GOT_TLSLD16_HA  R_PPC = 86 // R_POWERPC_GOT_TLSLD16_HA
            R_PPC_GOT_TPREL16     R_PPC = 87 // R_POWERPC_GOT_TPREL16
            R_PPC_GOT_TPREL16_LO  R_PPC = 88 // R_POWERPC_GOT_TPREL16_LO
            R_PPC_GOT_TPREL16_HI  R_PPC = 89 // R_POWERPC_GOT_TPREL16_HI
            R_PPC_GOT_TPREL16_HA  R_PPC = 90 // R_POWERPC_GOT_TPREL16_HA
            R_PPC_EMB_NADDR32     R_PPC = 101
            R_PPC_EMB_NADDR16     R_PPC = 102
            R_PPC_EMB_NADDR16_LO  R_PPC = 103
            R_PPC_EMB_NADDR16_HI  R_PPC = 104
            R_PPC_EMB_NADDR16_HA  R_PPC = 105
            R_PPC_EMB_SDAI16      R_PPC = 106
            R_PPC_EMB_SDA2I16     R_PPC = 107
            R_PPC_EMB_SDA2REL     R_PPC = 108
            R_PPC_EMB_SDA21       R_PPC = 109
            R_PPC_EMB_MRKREF      R_PPC = 110
            R_PPC_EMB_RELSEC16    R_PPC = 111
            R_PPC_EMB_RELST_LO    R_PPC = 112
            R_PPC_EMB_RELST_HI    R_PPC = 113
            R_PPC_EMB_RELST_HA    R_PPC = 114
            R_PPC_EMB_BIT_FLD     R_PPC = 115
            R_PPC_EMB_RELSDA      R_PPC = 116
        )

        func (R_PPC) GoString

        func (i R_PPC) GoString() string

        func (R_PPC) String

        func (i R_PPC) String() string

        type R_PPC64

        Relocation types for 64-bit PowerPC or Power Architecture processors.

        Values that are shared by both R_PPC and R_PPC64 are prefixed with R_POWERPC_ in the ELF standard. For the R_PPC64 type, the relevant shared relocations have been renamed with the prefix R_PPC64_. The original name follows the value in a comment.

        type R_PPC64 int
        const (
            R_PPC64_NONE               R_PPC64 = 0  // R_POWERPC_NONE
            R_PPC64_ADDR32             R_PPC64 = 1  // R_POWERPC_ADDR32
            R_PPC64_ADDR24             R_PPC64 = 2  // R_POWERPC_ADDR24
            R_PPC64_ADDR16             R_PPC64 = 3  // R_POWERPC_ADDR16
            R_PPC64_ADDR16_LO          R_PPC64 = 4  // R_POWERPC_ADDR16_LO
            R_PPC64_ADDR16_HI          R_PPC64 = 5  // R_POWERPC_ADDR16_HI
            R_PPC64_ADDR16_HA          R_PPC64 = 6  // R_POWERPC_ADDR16_HA
            R_PPC64_ADDR14             R_PPC64 = 7  // R_POWERPC_ADDR14
            R_PPC64_ADDR14_BRTAKEN     R_PPC64 = 8  // R_POWERPC_ADDR14_BRTAKEN
            R_PPC64_ADDR14_BRNTAKEN    R_PPC64 = 9  // R_POWERPC_ADDR14_BRNTAKEN
            R_PPC64_REL24              R_PPC64 = 10 // R_POWERPC_REL24
            R_PPC64_REL14              R_PPC64 = 11 // R_POWERPC_REL14
            R_PPC64_REL14_BRTAKEN      R_PPC64 = 12 // R_POWERPC_REL14_BRTAKEN
            R_PPC64_REL14_BRNTAKEN     R_PPC64 = 13 // R_POWERPC_REL14_BRNTAKEN
            R_PPC64_GOT16              R_PPC64 = 14 // R_POWERPC_GOT16
            R_PPC64_GOT16_LO           R_PPC64 = 15 // R_POWERPC_GOT16_LO
            R_PPC64_GOT16_HI           R_PPC64 = 16 // R_POWERPC_GOT16_HI
            R_PPC64_GOT16_HA           R_PPC64 = 17 // R_POWERPC_GOT16_HA
            R_PPC64_COPY               R_PPC64 = 19 // R_POWERPC_COPY
            R_PPC64_GLOB_DAT           R_PPC64 = 20 // R_POWERPC_GLOB_DAT
            R_PPC64_JMP_SLOT           R_PPC64 = 21 // R_POWERPC_JMP_SLOT
            R_PPC64_RELATIVE           R_PPC64 = 22 // R_POWERPC_RELATIVE
            R_PPC64_UADDR32            R_PPC64 = 24 // R_POWERPC_UADDR32
            R_PPC64_UADDR16            R_PPC64 = 25 // R_POWERPC_UADDR16
            R_PPC64_REL32              R_PPC64 = 26 // R_POWERPC_REL32
            R_PPC64_PLT32              R_PPC64 = 27 // R_POWERPC_PLT32
            R_PPC64_PLTREL32           R_PPC64 = 28 // R_POWERPC_PLTREL32
            R_PPC64_PLT16_LO           R_PPC64 = 29 // R_POWERPC_PLT16_LO
            R_PPC64_PLT16_HI           R_PPC64 = 30 // R_POWERPC_PLT16_HI
            R_PPC64_PLT16_HA           R_PPC64 = 31 // R_POWERPC_PLT16_HA
            R_PPC64_SECTOFF            R_PPC64 = 33 // R_POWERPC_SECTOFF
            R_PPC64_SECTOFF_LO         R_PPC64 = 34 // R_POWERPC_SECTOFF_LO
            R_PPC64_SECTOFF_HI         R_PPC64 = 35 // R_POWERPC_SECTOFF_HI
            R_PPC64_SECTOFF_HA         R_PPC64 = 36 // R_POWERPC_SECTOFF_HA
            R_PPC64_REL30              R_PPC64 = 37 // R_POWERPC_ADDR30
            R_PPC64_ADDR64             R_PPC64 = 38
            R_PPC64_ADDR16_HIGHER      R_PPC64 = 39
            R_PPC64_ADDR16_HIGHERA     R_PPC64 = 40
            R_PPC64_ADDR16_HIGHEST     R_PPC64 = 41
            R_PPC64_ADDR16_HIGHESTA    R_PPC64 = 42
            R_PPC64_UADDR64            R_PPC64 = 43
            R_PPC64_REL64              R_PPC64 = 44
            R_PPC64_PLT64              R_PPC64 = 45
            R_PPC64_PLTREL64           R_PPC64 = 46
            R_PPC64_TOC16              R_PPC64 = 47
            R_PPC64_TOC16_LO           R_PPC64 = 48
            R_PPC64_TOC16_HI           R_PPC64 = 49
            R_PPC64_TOC16_HA           R_PPC64 = 50
            R_PPC64_TOC                R_PPC64 = 51
            R_PPC64_PLTGOT16           R_PPC64 = 52
            R_PPC64_PLTGOT16_LO        R_PPC64 = 53
            R_PPC64_PLTGOT16_HI        R_PPC64 = 54
            R_PPC64_PLTGOT16_HA        R_PPC64 = 55
            R_PPC64_ADDR16_DS          R_PPC64 = 56
            R_PPC64_ADDR16_LO_DS       R_PPC64 = 57
            R_PPC64_GOT16_DS           R_PPC64 = 58
            R_PPC64_GOT16_LO_DS        R_PPC64 = 59
            R_PPC64_PLT16_LO_DS        R_PPC64 = 60
            R_PPC64_SECTOFF_DS         R_PPC64 = 61
            R_PPC64_SECTOFF_LO_DS      R_PPC64 = 62
            R_PPC64_TOC16_DS           R_PPC64 = 63
            R_PPC64_TOC16_LO_DS        R_PPC64 = 64
            R_PPC64_PLTGOT16_DS        R_PPC64 = 65
            R_PPC64_PLTGOT_LO_DS       R_PPC64 = 66
            R_PPC64_TLS                R_PPC64 = 67 // R_POWERPC_TLS
            R_PPC64_DTPMOD64           R_PPC64 = 68 // R_POWERPC_DTPMOD64
            R_PPC64_TPREL16            R_PPC64 = 69 // R_POWERPC_TPREL16
            R_PPC64_TPREL16_LO         R_PPC64 = 70 // R_POWERPC_TPREL16_LO
            R_PPC64_TPREL16_HI         R_PPC64 = 71 // R_POWERPC_TPREL16_HI
            R_PPC64_TPREL16_HA         R_PPC64 = 72 // R_POWERPC_TPREL16_HA
            R_PPC64_TPREL64            R_PPC64 = 73 // R_POWERPC_TPREL64
            R_PPC64_DTPREL16           R_PPC64 = 74 // R_POWERPC_DTPREL16
            R_PPC64_DTPREL16_LO        R_PPC64 = 75 // R_POWERPC_DTPREL16_LO
            R_PPC64_DTPREL16_HI        R_PPC64 = 76 // R_POWERPC_DTPREL16_HI
            R_PPC64_DTPREL16_HA        R_PPC64 = 77 // R_POWERPC_DTPREL16_HA
            R_PPC64_DTPREL64           R_PPC64 = 78 // R_POWERPC_DTPREL64
            R_PPC64_GOT_TLSGD16        R_PPC64 = 79 // R_POWERPC_GOT_TLSGD16
            R_PPC64_GOT_TLSGD16_LO     R_PPC64 = 80 // R_POWERPC_GOT_TLSGD16_LO
            R_PPC64_GOT_TLSGD16_HI     R_PPC64 = 81 // R_POWERPC_GOT_TLSGD16_HI
            R_PPC64_GOT_TLSGD16_HA     R_PPC64 = 82 // R_POWERPC_GOT_TLSGD16_HA
            R_PPC64_GOT_TLSLD16        R_PPC64 = 83 // R_POWERPC_GOT_TLSLD16
            R_PPC64_GOT_TLSLD16_LO     R_PPC64 = 84 // R_POWERPC_GOT_TLSLD16_LO
            R_PPC64_GOT_TLSLD16_HI     R_PPC64 = 85 // R_POWERPC_GOT_TLSLD16_HI
            R_PPC64_GOT_TLSLD16_HA     R_PPC64 = 86 // R_POWERPC_GOT_TLSLD16_HA
            R_PPC64_GOT_TPREL16_DS     R_PPC64 = 87 // R_POWERPC_GOT_TPREL16_DS
            R_PPC64_GOT_TPREL16_LO_DS  R_PPC64 = 88 // R_POWERPC_GOT_TPREL16_LO_DS
            R_PPC64_GOT_TPREL16_HI     R_PPC64 = 89 // R_POWERPC_GOT_TPREL16_HI
            R_PPC64_GOT_TPREL16_HA     R_PPC64 = 90 // R_POWERPC_GOT_TPREL16_HA
            R_PPC64_GOT_DTPREL16_DS    R_PPC64 = 91 // R_POWERPC_GOT_DTPREL16_DS
            R_PPC64_GOT_DTPREL16_LO_DS R_PPC64 = 92 // R_POWERPC_GOT_DTPREL16_LO_DS
            R_PPC64_GOT_DTPREL16_HI    R_PPC64 = 93 // R_POWERPC_GOT_DTPREL16_HI
            R_PPC64_GOT_DTPREL16_HA    R_PPC64 = 94 // R_POWERPC_GOT_DTPREL16_HA
            R_PPC64_TPREL16_DS         R_PPC64 = 95
            R_PPC64_TPREL16_LO_DS      R_PPC64 = 96
            R_PPC64_TPREL16_HIGHER     R_PPC64 = 97
            R_PPC64_TPREL16_HIGHERA    R_PPC64 = 98
            R_PPC64_TPREL16_HIGHEST    R_PPC64 = 99
            R_PPC64_TPREL16_HIGHESTA   R_PPC64 = 100
            R_PPC64_DTPREL16_DS        R_PPC64 = 101
            R_PPC64_DTPREL16_LO_DS     R_PPC64 = 102
            R_PPC64_DTPREL16_HIGHER    R_PPC64 = 103
            R_PPC64_DTPREL16_HIGHERA   R_PPC64 = 104
            R_PPC64_DTPREL16_HIGHEST   R_PPC64 = 105
            R_PPC64_DTPREL16_HIGHESTA  R_PPC64 = 106
            R_PPC64_TLSGD              R_PPC64 = 107
            R_PPC64_TLSLD              R_PPC64 = 108
            R_PPC64_TOCSAVE            R_PPC64 = 109
            R_PPC64_ADDR16_HIGH        R_PPC64 = 110
            R_PPC64_ADDR16_HIGHA       R_PPC64 = 111
            R_PPC64_TPREL16_HIGH       R_PPC64 = 112
            R_PPC64_TPREL16_HIGHA      R_PPC64 = 113
            R_PPC64_DTPREL16_HIGH      R_PPC64 = 114
            R_PPC64_DTPREL16_HIGHA     R_PPC64 = 115
            R_PPC64_REL24_NOTOC        R_PPC64 = 116
            R_PPC64_ADDR64_LOCAL       R_PPC64 = 117
            R_PPC64_ENTRY              R_PPC64 = 118
            R_PPC64_PLTSEQ             R_PPC64 = 119
            R_PPC64_PLTCALL            R_PPC64 = 120
            R_PPC64_PLTSEQ_NOTOC       R_PPC64 = 121
            R_PPC64_PLTCALL_NOTOC      R_PPC64 = 122
            R_PPC64_PCREL_OPT          R_PPC64 = 123
            R_PPC64_REL24_P9NOTOC      R_PPC64 = 124
            R_PPC64_D34                R_PPC64 = 128
            R_PPC64_D34_LO             R_PPC64 = 129
            R_PPC64_D34_HI30           R_PPC64 = 130
            R_PPC64_D34_HA30           R_PPC64 = 131
            R_PPC64_PCREL34            R_PPC64 = 132
            R_PPC64_GOT_PCREL34        R_PPC64 = 133
            R_PPC64_PLT_PCREL34        R_PPC64 = 134
            R_PPC64_PLT_PCREL34_NOTOC  R_PPC64 = 135
            R_PPC64_ADDR16_HIGHER34    R_PPC64 = 136
            R_PPC64_ADDR16_HIGHERA34   R_PPC64 = 137
            R_PPC64_ADDR16_HIGHEST34   R_PPC64 = 138
            R_PPC64_ADDR16_HIGHESTA34  R_PPC64 = 139
            R_PPC64_REL16_HIGHER34     R_PPC64 = 140
            R_PPC64_REL16_HIGHERA34    R_PPC64 = 141
            R_PPC64_REL16_HIGHEST34    R_PPC64 = 142
            R_PPC64_REL16_HIGHESTA34   R_PPC64 = 143
            R_PPC64_D28                R_PPC64 = 144
            R_PPC64_PCREL28            R_PPC64 = 145
            R_PPC64_TPREL34            R_PPC64 = 146
            R_PPC64_DTPREL34           R_PPC64 = 147
            R_PPC64_GOT_TLSGD_PCREL34  R_PPC64 = 148
            R_PPC64_GOT_TLSLD_PCREL34  R_PPC64 = 149
            R_PPC64_GOT_TPREL_PCREL34  R_PPC64 = 150
            R_PPC64_GOT_DTPREL_PCREL34 R_PPC64 = 151
            R_PPC64_REL16_HIGH         R_PPC64 = 240
            R_PPC64_REL16_HIGHA        R_PPC64 = 241
            R_PPC64_REL16_HIGHER       R_PPC64 = 242
            R_PPC64_REL16_HIGHERA      R_PPC64 = 243
            R_PPC64_REL16_HIGHEST      R_PPC64 = 244
            R_PPC64_REL16_HIGHESTA     R_PPC64 = 245
            R_PPC64_REL16DX_HA         R_PPC64 = 246 // R_POWERPC_REL16DX_HA
            R_PPC64_JMP_IREL           R_PPC64 = 247
            R_PPC64_IRELATIVE          R_PPC64 = 248 // R_POWERPC_IRELATIVE
            R_PPC64_REL16              R_PPC64 = 249 // R_POWERPC_REL16
            R_PPC64_REL16_LO           R_PPC64 = 250 // R_POWERPC_REL16_LO
            R_PPC64_REL16_HI           R_PPC64 = 251 // R_POWERPC_REL16_HI
            R_PPC64_REL16_HA           R_PPC64 = 252 // R_POWERPC_REL16_HA
            R_PPC64_GNU_VTINHERIT      R_PPC64 = 253
            R_PPC64_GNU_VTENTRY        R_PPC64 = 254
        )

        func (R_PPC64) GoString

        func (i R_PPC64) GoString() string

        func (R_PPC64) String

        func (i R_PPC64) String() string

        type R_RISCV

        Relocation types for RISC-V processors.

        type R_RISCV int
        const (
            R_RISCV_NONE          R_RISCV = 0  /* No relocation. */
            R_RISCV_32            R_RISCV = 1  /* Add 32 bit zero extended symbol value */
            R_RISCV_64            R_RISCV = 2  /* Add 64 bit symbol value. */
            R_RISCV_RELATIVE      R_RISCV = 3  /* Add load address of shared object. */
            R_RISCV_COPY          R_RISCV = 4  /* Copy data from shared object. */
            R_RISCV_JUMP_SLOT     R_RISCV = 5  /* Set GOT entry to code address. */
            R_RISCV_TLS_DTPMOD32  R_RISCV = 6  /* 32 bit ID of module containing symbol */
            R_RISCV_TLS_DTPMOD64  R_RISCV = 7  /* ID of module containing symbol */
            R_RISCV_TLS_DTPREL32  R_RISCV = 8  /* 32 bit relative offset in TLS block */
            R_RISCV_TLS_DTPREL64  R_RISCV = 9  /* Relative offset in TLS block */
            R_RISCV_TLS_TPREL32   R_RISCV = 10 /* 32 bit relative offset in static TLS block */
            R_RISCV_TLS_TPREL64   R_RISCV = 11 /* Relative offset in static TLS block */
            R_RISCV_BRANCH        R_RISCV = 16 /* PC-relative branch */
            R_RISCV_JAL           R_RISCV = 17 /* PC-relative jump */
            R_RISCV_CALL          R_RISCV = 18 /* PC-relative call */
            R_RISCV_CALL_PLT      R_RISCV = 19 /* PC-relative call (PLT) */
            R_RISCV_GOT_HI20      R_RISCV = 20 /* PC-relative GOT reference */
            R_RISCV_TLS_GOT_HI20  R_RISCV = 21 /* PC-relative TLS IE GOT offset */
            R_RISCV_TLS_GD_HI20   R_RISCV = 22 /* PC-relative TLS GD reference */
            R_RISCV_PCREL_HI20    R_RISCV = 23 /* PC-relative reference */
            R_RISCV_PCREL_LO12_I  R_RISCV = 24 /* PC-relative reference */
            R_RISCV_PCREL_LO12_S  R_RISCV = 25 /* PC-relative reference */
            R_RISCV_HI20          R_RISCV = 26 /* Absolute address */
            R_RISCV_LO12_I        R_RISCV = 27 /* Absolute address */
            R_RISCV_LO12_S        R_RISCV = 28 /* Absolute address */
            R_RISCV_TPREL_HI20    R_RISCV = 29 /* TLS LE thread offset */
            R_RISCV_TPREL_LO12_I  R_RISCV = 30 /* TLS LE thread offset */
            R_RISCV_TPREL_LO12_S  R_RISCV = 31 /* TLS LE thread offset */
            R_RISCV_TPREL_ADD     R_RISCV = 32 /* TLS LE thread usage */
            R_RISCV_ADD8          R_RISCV = 33 /* 8-bit label addition */
            R_RISCV_ADD16         R_RISCV = 34 /* 16-bit label addition */
            R_RISCV_ADD32         R_RISCV = 35 /* 32-bit label addition */
            R_RISCV_ADD64         R_RISCV = 36 /* 64-bit label addition */
            R_RISCV_SUB8          R_RISCV = 37 /* 8-bit label subtraction */
            R_RISCV_SUB16         R_RISCV = 38 /* 16-bit label subtraction */
            R_RISCV_SUB32         R_RISCV = 39 /* 32-bit label subtraction */
            R_RISCV_SUB64         R_RISCV = 40 /* 64-bit label subtraction */
            R_RISCV_GNU_VTINHERIT R_RISCV = 41 /* GNU C++ vtable hierarchy */
            R_RISCV_GNU_VTENTRY   R_RISCV = 42 /* GNU C++ vtable member usage */
            R_RISCV_ALIGN         R_RISCV = 43 /* Alignment statement */
            R_RISCV_RVC_BRANCH    R_RISCV = 44 /* PC-relative branch offset */
            R_RISCV_RVC_JUMP      R_RISCV = 45 /* PC-relative jump offset */
            R_RISCV_RVC_LUI       R_RISCV = 46 /* Absolute address */
            R_RISCV_GPREL_I       R_RISCV = 47 /* GP-relative reference */
            R_RISCV_GPREL_S       R_RISCV = 48 /* GP-relative reference */
            R_RISCV_TPREL_I       R_RISCV = 49 /* TP-relative TLS LE load */
            R_RISCV_TPREL_S       R_RISCV = 50 /* TP-relative TLS LE store */
            R_RISCV_RELAX         R_RISCV = 51 /* Instruction pair can be relaxed */
            R_RISCV_SUB6          R_RISCV = 52 /* Local label subtraction */
            R_RISCV_SET6          R_RISCV = 53 /* Local label subtraction */
            R_RISCV_SET8          R_RISCV = 54 /* Local label subtraction */
            R_RISCV_SET16         R_RISCV = 55 /* Local label subtraction */
            R_RISCV_SET32         R_RISCV = 56 /* Local label subtraction */
            R_RISCV_32_PCREL      R_RISCV = 57 /* 32-bit PC relative */
        )

        func (R_RISCV) GoString

        func (i R_RISCV) GoString() string

        func (R_RISCV) String

        func (i R_RISCV) String() string

        type R_SPARC

        Relocation types for SPARC.

        type R_SPARC int
        const (
            R_SPARC_NONE     R_SPARC = 0
            R_SPARC_8        R_SPARC = 1
            R_SPARC_16       R_SPARC = 2
            R_SPARC_32       R_SPARC = 3
            R_SPARC_DISP8    R_SPARC = 4
            R_SPARC_DISP16   R_SPARC = 5
            R_SPARC_DISP32   R_SPARC = 6
            R_SPARC_WDISP30  R_SPARC = 7
            R_SPARC_WDISP22  R_SPARC = 8
            R_SPARC_HI22     R_SPARC = 9
            R_SPARC_22       R_SPARC = 10
            R_SPARC_13       R_SPARC = 11
            R_SPARC_LO10     R_SPARC = 12
            R_SPARC_GOT10    R_SPARC = 13
            R_SPARC_GOT13    R_SPARC = 14
            R_SPARC_GOT22    R_SPARC = 15
            R_SPARC_PC10     R_SPARC = 16
            R_SPARC_PC22     R_SPARC = 17
            R_SPARC_WPLT30   R_SPARC = 18
            R_SPARC_COPY     R_SPARC = 19
            R_SPARC_GLOB_DAT R_SPARC = 20
            R_SPARC_JMP_SLOT R_SPARC = 21
            R_SPARC_RELATIVE R_SPARC = 22
            R_SPARC_UA32     R_SPARC = 23
            R_SPARC_PLT32    R_SPARC = 24
            R_SPARC_HIPLT22  R_SPARC = 25
            R_SPARC_LOPLT10  R_SPARC = 26
            R_SPARC_PCPLT32  R_SPARC = 27
            R_SPARC_PCPLT22  R_SPARC = 28
            R_SPARC_PCPLT10  R_SPARC = 29
            R_SPARC_10       R_SPARC = 30
            R_SPARC_11       R_SPARC = 31
            R_SPARC_64       R_SPARC = 32
            R_SPARC_OLO10    R_SPARC = 33
            R_SPARC_HH22     R_SPARC = 34
            R_SPARC_HM10     R_SPARC = 35
            R_SPARC_LM22     R_SPARC = 36
            R_SPARC_PC_HH22  R_SPARC = 37
            R_SPARC_PC_HM10  R_SPARC = 38
            R_SPARC_PC_LM22  R_SPARC = 39
            R_SPARC_WDISP16  R_SPARC = 40
            R_SPARC_WDISP19  R_SPARC = 41
            R_SPARC_GLOB_JMP R_SPARC = 42
            R_SPARC_7        R_SPARC = 43
            R_SPARC_5        R_SPARC = 44
            R_SPARC_6        R_SPARC = 45
            R_SPARC_DISP64   R_SPARC = 46
            R_SPARC_PLT64    R_SPARC = 47
            R_SPARC_HIX22    R_SPARC = 48
            R_SPARC_LOX10    R_SPARC = 49
            R_SPARC_H44      R_SPARC = 50
            R_SPARC_M44      R_SPARC = 51
            R_SPARC_L44      R_SPARC = 52
            R_SPARC_REGISTER R_SPARC = 53
            R_SPARC_UA64     R_SPARC = 54
            R_SPARC_UA16     R_SPARC = 55
        )

        func (R_SPARC) GoString

        func (i R_SPARC) GoString() string

        func (R_SPARC) String

        func (i R_SPARC) String() string

        type R_X86_64

        Relocation types for x86-64.

        type R_X86_64 int
        const (
            R_X86_64_NONE            R_X86_64 = 0  /* No relocation. */
            R_X86_64_64              R_X86_64 = 1  /* Add 64 bit symbol value. */
            R_X86_64_PC32            R_X86_64 = 2  /* PC-relative 32 bit signed sym value. */
            R_X86_64_GOT32           R_X86_64 = 3  /* PC-relative 32 bit GOT offset. */
            R_X86_64_PLT32           R_X86_64 = 4  /* PC-relative 32 bit PLT offset. */
            R_X86_64_COPY            R_X86_64 = 5  /* Copy data from shared object. */
            R_X86_64_GLOB_DAT        R_X86_64 = 6  /* Set GOT entry to data address. */
            R_X86_64_JMP_SLOT        R_X86_64 = 7  /* Set GOT entry to code address. */
            R_X86_64_RELATIVE        R_X86_64 = 8  /* Add load address of shared object. */
            R_X86_64_GOTPCREL        R_X86_64 = 9  /* Add 32 bit signed pcrel offset to GOT. */
            R_X86_64_32              R_X86_64 = 10 /* Add 32 bit zero extended symbol value */
            R_X86_64_32S             R_X86_64 = 11 /* Add 32 bit sign extended symbol value */
            R_X86_64_16              R_X86_64 = 12 /* Add 16 bit zero extended symbol value */
            R_X86_64_PC16            R_X86_64 = 13 /* Add 16 bit signed extended pc relative symbol value */
            R_X86_64_8               R_X86_64 = 14 /* Add 8 bit zero extended symbol value */
            R_X86_64_PC8             R_X86_64 = 15 /* Add 8 bit signed extended pc relative symbol value */
            R_X86_64_DTPMOD64        R_X86_64 = 16 /* ID of module containing symbol */
            R_X86_64_DTPOFF64        R_X86_64 = 17 /* Offset in TLS block */
            R_X86_64_TPOFF64         R_X86_64 = 18 /* Offset in static TLS block */
            R_X86_64_TLSGD           R_X86_64 = 19 /* PC relative offset to GD GOT entry */
            R_X86_64_TLSLD           R_X86_64 = 20 /* PC relative offset to LD GOT entry */
            R_X86_64_DTPOFF32        R_X86_64 = 21 /* Offset in TLS block */
            R_X86_64_GOTTPOFF        R_X86_64 = 22 /* PC relative offset to IE GOT entry */
            R_X86_64_TPOFF32         R_X86_64 = 23 /* Offset in static TLS block */
            R_X86_64_PC64            R_X86_64 = 24 /* PC relative 64-bit sign extended symbol value. */
            R_X86_64_GOTOFF64        R_X86_64 = 25
            R_X86_64_GOTPC32         R_X86_64 = 26
            R_X86_64_GOT64           R_X86_64 = 27
            R_X86_64_GOTPCREL64      R_X86_64 = 28
            R_X86_64_GOTPC64         R_X86_64 = 29
            R_X86_64_GOTPLT64        R_X86_64 = 30
            R_X86_64_PLTOFF64        R_X86_64 = 31
            R_X86_64_SIZE32          R_X86_64 = 32
            R_X86_64_SIZE64          R_X86_64 = 33
            R_X86_64_GOTPC32_TLSDESC R_X86_64 = 34
            R_X86_64_TLSDESC_CALL    R_X86_64 = 35
            R_X86_64_TLSDESC         R_X86_64 = 36
            R_X86_64_IRELATIVE       R_X86_64 = 37
            R_X86_64_RELATIVE64      R_X86_64 = 38
            R_X86_64_PC32_BND        R_X86_64 = 39
            R_X86_64_PLT32_BND       R_X86_64 = 40
            R_X86_64_GOTPCRELX       R_X86_64 = 41
            R_X86_64_REX_GOTPCRELX   R_X86_64 = 42
        )

        func (R_X86_64) GoString

        func (i R_X86_64) GoString() string

        func (R_X86_64) String

        func (i R_X86_64) String() string

        type Rel32

        ELF32 Relocations that don't need an addend field.

        type Rel32 struct {
            Off  uint32 /* Location to be relocated. */
            Info uint32 /* Relocation type and symbol index. */
        }
        

        type Rel64

        ELF64 relocations that don't need an addend field.

        type Rel64 struct {
            Off  uint64 /* Location to be relocated. */
            Info uint64 /* Relocation type and symbol index. */
        }
        

        type Rela32

        ELF32 Relocations that need an addend field.

        type Rela32 struct {
            Off    uint32 /* Location to be relocated. */
            Info   uint32 /* Relocation type and symbol index. */
            Addend int32  /* Addend. */
        }
        

        type Rela64

        ELF64 relocations that need an addend field.

        type Rela64 struct {
            Off    uint64 /* Location to be relocated. */
            Info   uint64 /* Relocation type and symbol index. */
            Addend int64  /* Addend. */
        }
        

        type Section

        A Section represents a single section in an ELF file.

        type Section struct {
            SectionHeader
        
            // Embed ReaderAt for ReadAt method.
            // Do not embed SectionReader directly
            // to avoid having Read and Seek.
            // If a client wants Read and Seek it must use
            // Open() to avoid fighting over the seek offset
            // with other clients.
            //
            // ReaderAt may be nil if the section is not easily available
            // in a random-access form. For example, a compressed section
            // may have a nil ReaderAt.
            io.ReaderAt
            // contains filtered or unexported fields
        }
        

        func (*Section) Data

        func (s *Section) Data() ([]byte, error)

        Data reads and returns the contents of the ELF section. Even if the section is stored compressed in the ELF file, Data returns uncompressed data.

        For an SHT_NOBITS section, Data always returns a non-nil error.

        func (*Section) Open

        func (s *Section) Open() io.ReadSeeker

        Open returns a new ReadSeeker reading the ELF section. Even if the section is stored compressed in the ELF file, the ReadSeeker reads uncompressed data.

        For an SHT_NOBITS section, all calls to the opened reader will return a non-nil error.

        type Section32

        ELF32 Section header.

        type Section32 struct {
            Name      uint32 /* Section name (index into the section header string table). */
            Type      uint32 /* Section type. */
            Flags     uint32 /* Section flags. */
            Addr      uint32 /* Address in memory image. */
            Off       uint32 /* Offset in file. */
            Size      uint32 /* Size in bytes. */
            Link      uint32 /* Index of a related section. */
            Info      uint32 /* Depends on section type. */
            Addralign uint32 /* Alignment in bytes. */
            Entsize   uint32 /* Size of each entry in section. */
        }
        

        type Section64

        ELF64 Section header.

        type Section64 struct {
            Name      uint32 /* Section name (index into the section header string table). */
            Type      uint32 /* Section type. */
            Flags     uint64 /* Section flags. */
            Addr      uint64 /* Address in memory image. */
            Off       uint64 /* Offset in file. */
            Size      uint64 /* Size in bytes. */
            Link      uint32 /* Index of a related section. */
            Info      uint32 /* Depends on section type. */
            Addralign uint64 /* Alignment in bytes. */
            Entsize   uint64 /* Size of each entry in section. */
        }
        

        type SectionFlag

        Section flags.

        type SectionFlag uint32
        const (
            SHF_WRITE            SectionFlag = 0x1        /* Section contains writable data. */
            SHF_ALLOC            SectionFlag = 0x2        /* Section occupies memory. */
            SHF_EXECINSTR        SectionFlag = 0x4        /* Section contains instructions. */
            SHF_MERGE            SectionFlag = 0x10       /* Section may be merged. */
            SHF_STRINGS          SectionFlag = 0x20       /* Section contains strings. */
            SHF_INFO_LINK        SectionFlag = 0x40       /* sh_info holds section index. */
            SHF_LINK_ORDER       SectionFlag = 0x80       /* Special ordering requirements. */
            SHF_OS_NONCONFORMING SectionFlag = 0x100      /* OS-specific processing required. */
            SHF_GROUP            SectionFlag = 0x200      /* Member of section group. */
            SHF_TLS              SectionFlag = 0x400      /* Section contains TLS data. */
            SHF_COMPRESSED       SectionFlag = 0x800      /* Section is compressed. */
            SHF_MASKOS           SectionFlag = 0x0ff00000 /* OS-specific semantics. */
            SHF_MASKPROC         SectionFlag = 0xf0000000 /* Processor-specific semantics. */
        )

        func (SectionFlag) GoString

        func (i SectionFlag) GoString() string

        func (SectionFlag) String

        func (i SectionFlag) String() string

        type SectionHeader

        A SectionHeader represents a single ELF section header.

        type SectionHeader struct {
            Name      string
            Type      SectionType
            Flags     SectionFlag
            Addr      uint64
            Offset    uint64
            Size      uint64
            Link      uint32
            Info      uint32
            Addralign uint64
            Entsize   uint64
        
            // FileSize is the size of this section in the file in bytes.
            // If a section is compressed, FileSize is the size of the
            // compressed data, while Size (above) is the size of the
            // uncompressed data.
            FileSize uint64
        }
        

        type SectionIndex

        Special section indices.

        type SectionIndex int
        const (
            SHN_UNDEF     SectionIndex = 0      /* Undefined, missing, irrelevant. */
            SHN_LORESERVE SectionIndex = 0xff00 /* First of reserved range. */
            SHN_LOPROC    SectionIndex = 0xff00 /* First processor-specific. */
            SHN_HIPROC    SectionIndex = 0xff1f /* Last processor-specific. */
            SHN_LOOS      SectionIndex = 0xff20 /* First operating system-specific. */
            SHN_HIOS      SectionIndex = 0xff3f /* Last operating system-specific. */
            SHN_ABS       SectionIndex = 0xfff1 /* Absolute values. */
            SHN_COMMON    SectionIndex = 0xfff2 /* Common data. */
            SHN_XINDEX    SectionIndex = 0xffff /* Escape; index stored elsewhere. */
            SHN_HIRESERVE SectionIndex = 0xffff /* Last of reserved range. */
        )

        func (SectionIndex) GoString

        func (i SectionIndex) GoString() string

        func (SectionIndex) String

        func (i SectionIndex) String() string

        type SectionType

        Section type.

        type SectionType uint32
        const (
            SHT_NULL           SectionType = 0          /* inactive */
            SHT_PROGBITS       SectionType = 1          /* program defined information */
            SHT_SYMTAB         SectionType = 2          /* symbol table section */
            SHT_STRTAB         SectionType = 3          /* string table section */
            SHT_RELA           SectionType = 4          /* relocation section with addends */
            SHT_HASH           SectionType = 5          /* symbol hash table section */
            SHT_DYNAMIC        SectionType = 6          /* dynamic section */
            SHT_NOTE           SectionType = 7          /* note section */
            SHT_NOBITS         SectionType = 8          /* no space section */
            SHT_REL            SectionType = 9          /* relocation section - no addends */
            SHT_SHLIB          SectionType = 10         /* reserved - purpose unknown */
            SHT_DYNSYM         SectionType = 11         /* dynamic symbol table section */
            SHT_INIT_ARRAY     SectionType = 14         /* Initialization function pointers. */
            SHT_FINI_ARRAY     SectionType = 15         /* Termination function pointers. */
            SHT_PREINIT_ARRAY  SectionType = 16         /* Pre-initialization function ptrs. */
            SHT_GROUP          SectionType = 17         /* Section group. */
            SHT_SYMTAB_SHNDX   SectionType = 18         /* Section indexes (see SHN_XINDEX). */
            SHT_LOOS           SectionType = 0x60000000 /* First of OS specific semantics */
            SHT_GNU_ATTRIBUTES SectionType = 0x6ffffff5 /* GNU object attributes */
            SHT_GNU_HASH       SectionType = 0x6ffffff6 /* GNU hash table */
            SHT_GNU_LIBLIST    SectionType = 0x6ffffff7 /* GNU prelink library list */
            SHT_GNU_VERDEF     SectionType = 0x6ffffffd /* GNU version definition section */
            SHT_GNU_VERNEED    SectionType = 0x6ffffffe /* GNU version needs section */
            SHT_GNU_VERSYM     SectionType = 0x6fffffff /* GNU version symbol table */
            SHT_HIOS           SectionType = 0x6fffffff /* Last of OS specific semantics */
            SHT_LOPROC         SectionType = 0x70000000 /* reserved range for processor */
            SHT_MIPS_ABIFLAGS  SectionType = 0x7000002a /* .MIPS.abiflags */
            SHT_HIPROC         SectionType = 0x7fffffff /* specific section header types */
            SHT_LOUSER         SectionType = 0x80000000 /* reserved range for application */
            SHT_HIUSER         SectionType = 0xffffffff /* specific indexes */
        )

        func (SectionType) GoString

        func (i SectionType) GoString() string

        func (SectionType) String

        func (i SectionType) String() string

        type Sym32

        ELF32 Symbol.

        type Sym32 struct {
            Name  uint32
            Value uint32
            Size  uint32
            Info  uint8
            Other uint8
            Shndx uint16
        }
        

        type Sym64

        ELF64 symbol table entries.

        type Sym64 struct {
            Name  uint32 /* String table index of name. */
            Info  uint8  /* Type and binding information. */
            Other uint8  /* Reserved (not used). */
            Shndx uint16 /* Section index of symbol. */
            Value uint64 /* Symbol value. */
            Size  uint64 /* Size of associated object. */
        }
        

        type SymBind

        Symbol Binding - ELFNN_ST_BIND - st_info

        type SymBind int
        const (
            STB_LOCAL  SymBind = 0  /* Local symbol */
            STB_GLOBAL SymBind = 1  /* Global symbol */
            STB_WEAK   SymBind = 2  /* like global - lower precedence */
            STB_LOOS   SymBind = 10 /* Reserved range for operating system */
            STB_HIOS   SymBind = 12 /*   specific semantics. */
            STB_LOPROC SymBind = 13 /* reserved range for processor */
            STB_HIPROC SymBind = 15 /*   specific semantics. */
        )

        func ST_BIND

        func ST_BIND(info uint8) SymBind

        func (SymBind) GoString

        func (i SymBind) GoString() string

        func (SymBind) String

        func (i SymBind) String() string

        type SymType

        Symbol type - ELFNN_ST_TYPE - st_info

        type SymType int
        const (
            STT_NOTYPE  SymType = 0  /* Unspecified type. */
            STT_OBJECT  SymType = 1  /* Data object. */
            STT_FUNC    SymType = 2  /* Function. */
            STT_SECTION SymType = 3  /* Section. */
            STT_FILE    SymType = 4  /* Source file. */
            STT_COMMON  SymType = 5  /* Uninitialized common block. */
            STT_TLS     SymType = 6  /* TLS object. */
            STT_LOOS    SymType = 10 /* Reserved range for operating system */
            STT_HIOS    SymType = 12 /*   specific semantics. */
            STT_LOPROC  SymType = 13 /* reserved range for processor */
            STT_HIPROC  SymType = 15 /*   specific semantics. */
        )

        func ST_TYPE

        func ST_TYPE(info uint8) SymType

        func (SymType) GoString

        func (i SymType) GoString() string

        func (SymType) String

        func (i SymType) String() string

        type SymVis

        Symbol visibility - ELFNN_ST_VISIBILITY - st_other

        type SymVis int
        const (
            STV_DEFAULT   SymVis = 0x0 /* Default visibility (see binding). */
            STV_INTERNAL  SymVis = 0x1 /* Special meaning in relocatable objects. */
            STV_HIDDEN    SymVis = 0x2 /* Not visible. */
            STV_PROTECTED SymVis = 0x3 /* Visible but not preemptible. */
        )

        func ST_VISIBILITY

        func ST_VISIBILITY(other uint8) SymVis

        func (SymVis) GoString

        func (i SymVis) GoString() string

        func (SymVis) String

        func (i SymVis) String() string

        type Symbol

        A Symbol represents an entry in an ELF symbol table section.

        type Symbol struct {
            Name        string
            Info, Other byte
            Section     SectionIndex
            Value, Size uint64
        
            // Version and Library are present only for the dynamic symbol
            // table.
            Version string
            Library string
        }
        

        type Type

        Type is found in Header.Type.

        type Type uint16
        const (
            ET_NONE   Type = 0      /* Unknown type. */
            ET_REL    Type = 1      /* Relocatable. */
            ET_EXEC   Type = 2      /* Executable. */
            ET_DYN    Type = 3      /* Shared object. */
            ET_CORE   Type = 4      /* Core file. */
            ET_LOOS   Type = 0xfe00 /* First operating system specific. */
            ET_HIOS   Type = 0xfeff /* Last operating system-specific. */
            ET_LOPROC Type = 0xff00 /* First processor-specific. */
            ET_HIPROC Type = 0xffff /* Last processor-specific. */
        )

        func (Type) GoString

        func (i Type) GoString() string

        func (Type) String

        func (i Type) String() string

        type Version

        Version is found in Header.Ident[EI_VERSION] and Header.Version.

        type Version byte
        const (
            EV_NONE    Version = 0
            EV_CURRENT Version = 1
        )

        func (Version) GoString

        func (i Version) GoString() string

        func (Version) String

        func (i Version) String() string
        gosym - Go Documentation Server
        ...

        Package gosym

        import "debug/gosym"
        Overview
        Index

        Overview ▾

        Package gosym implements access to the Go symbol and line number tables embedded in Go binaries generated by the gc compilers.

        type DecodingError

        DecodingError represents an error during the decoding of the symbol table.

        type DecodingError struct {
            // contains filtered or unexported fields
        }
        

        func (*DecodingError) Error

        func (e *DecodingError) Error() string

        type Func

        A Func collects information about a single function.

        type Func struct {
            Entry uint64
            *Sym
            End       uint64
            Params    []*Sym // nil for Go 1.3 and later binaries
            Locals    []*Sym // nil for Go 1.3 and later binaries
            FrameSize int
            LineTable *LineTable
            Obj       *Obj
        }
        

        type LineTable

        A LineTable is a data structure mapping program counters to line numbers.

        In Go 1.1 and earlier, each function (represented by a Func) had its own LineTable, and the line number corresponded to a numbering of all source lines in the program, across all files. That absolute line number would then have to be converted separately to a file name and line number within the file.

        In Go 1.2, the format of the data changed so that there is a single LineTable for the entire program, shared by all Funcs, and there are no absolute line numbers, just line numbers within specific files.

        For the most part, LineTable's methods should be treated as an internal detail of the package; callers should use the methods on Table instead.

        type LineTable struct {
            Data []byte
            PC   uint64
            Line int
            // contains filtered or unexported fields
        }
        

        func NewLineTable

        func NewLineTable(data []byte, text uint64) *LineTable

        NewLineTable returns a new PC/line table corresponding to the encoded data. Text must be the start address of the corresponding text segment.

        func (*LineTable) LineToPC

        func (t *LineTable) LineToPC(line int, maxpc uint64) uint64

        LineToPC returns the program counter for the given line number, considering only program counters before maxpc.

        Deprecated: Use Table's LineToPC method instead.

        func (*LineTable) PCToLine

        func (t *LineTable) PCToLine(pc uint64) int

        PCToLine returns the line number for the given program counter.

        Deprecated: Use Table's PCToLine method instead.

        type Obj

        An Obj represents a collection of functions in a symbol table.

        The exact method of division of a binary into separate Objs is an internal detail of the symbol table format.

        In early versions of Go each source file became a different Obj.

        In Go 1 and Go 1.1, each package produced one Obj for all Go sources and one Obj per C source file.

        In Go 1.2, there is a single Obj for the entire program.

        type Obj struct {
            // Funcs is a list of functions in the Obj.
            Funcs []Func
        
            // In Go 1.1 and earlier, Paths is a list of symbols corresponding
            // to the source file names that produced the Obj.
            // In Go 1.2, Paths is nil.
            // Use the keys of Table.Files to obtain a list of source files.
            Paths []Sym // meta
        }
        

        type Sym

        A Sym represents a single symbol table entry.

        type Sym struct {
            Value  uint64
            Type   byte
            Name   string
            GoType uint64
            // If this symbol is a function symbol, the corresponding Func
            Func *Func
            // contains filtered or unexported fields
        }
        

        func (*Sym) BaseName

        func (s *Sym) BaseName() string

        BaseName returns the symbol name without the package or receiver name.

        func (*Sym) PackageName

        func (s *Sym) PackageName() string

        PackageName returns the package part of the symbol name, or the empty string if there is none.

        func (*Sym) ReceiverName

        func (s *Sym) ReceiverName() string

        ReceiverName returns the receiver type name of this symbol, or the empty string if there is none. A receiver name is only detected in the case that s.Name is fully-specified with a package name.

        func (*Sym) Static

        func (s *Sym) Static() bool

        Static reports whether this symbol is static (not visible outside its file).

        type Table

        Table represents a Go symbol table. It stores all of the symbols decoded from the program and provides methods to translate between symbols, names, and addresses.

        type Table struct {
            Syms  []Sym // nil for Go 1.3 and later binaries
            Funcs []Func
            Files map[string]*Obj // for Go 1.2 and later all files map to one Obj
            Objs  []Obj           // for Go 1.2 and later only one Obj in slice
            // contains filtered or unexported fields
        }
        

        func NewTable

        func NewTable(symtab []byte, pcln *LineTable) (*Table, error)

        NewTable decodes the Go symbol table (the ".gosymtab" section in ELF), returning an in-memory representation. Starting with Go 1.3, the Go symbol table no longer includes symbol data.

        func (*Table) LineToPC

        func (t *Table) LineToPC(file string, line int) (pc uint64, fn *Func, err error)

        LineToPC looks up the first program counter on the given line in the named file. It returns UnknownFileError or UnknownLineError if there is an error looking up this line.

        func (*Table) LookupFunc

        func (t *Table) LookupFunc(name string) *Func

        LookupFunc returns the text, data, or bss symbol with the given name, or nil if no such symbol is found.

        func (*Table) LookupSym

        func (t *Table) LookupSym(name string) *Sym

        LookupSym returns the text, data, or bss symbol with the given name, or nil if no such symbol is found.

        func (*Table) PCToFunc

        func (t *Table) PCToFunc(pc uint64) *Func

        PCToFunc returns the function containing the program counter pc, or nil if there is no such function.

        func (*Table) PCToLine

        func (t *Table) PCToLine(pc uint64) (file string, line int, fn *Func)

        PCToLine looks up line number information for a program counter. If there is no information, it returns fn == nil.

        func (*Table) SymByAddr

        func (t *Table) SymByAddr(addr uint64) *Sym

        SymByAddr returns the text, data, or bss symbol starting at the given address.

        type UnknownFileError

        UnknownFileError represents a failure to find the specific file in the symbol table.

        type UnknownFileError string

        func (UnknownFileError) Error

        func (e UnknownFileError) Error() string

        type UnknownLineError

        UnknownLineError represents a failure to map a line to a program counter, either because the line is beyond the bounds of the file or because there is no code on the given line.

        type UnknownLineError struct {
            File string
            Line int
        }
        

        func (*UnknownLineError) Error

        func (e *UnknownLineError) Error() string
        macho - Go Documentation Server
        ...

        Package macho

        import "debug/macho"
        Overview
        Index

        Overview ▾

        Package macho implements access to Mach-O object files.

        Security

        This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

        Index ▾

        Constants
        Variables
        type Cpu
            func (i Cpu) GoString() string
            func (i Cpu) String() string
        type Dylib
        type DylibCmd
        type Dysymtab
        type DysymtabCmd
        type FatArch
        type FatArchHeader
        type FatFile
            func NewFatFile(r io.ReaderAt) (*FatFile, error)
            func OpenFat(name string) (*FatFile, error)
            func (ff *FatFile) Close() error
        type File
            func NewFile(r io.ReaderAt) (*File, error)
            func Open(name string) (*File, error)
            func (f *File) Close() error
            func (f *File) DWARF() (*dwarf.Data, error)
            func (f *File) ImportedLibraries() ([]string, error)
            func (f *File) ImportedSymbols() ([]string, error)
            func (f *File) Section(name string) *Section
            func (f *File) Segment(name string) *Segment
        type FileHeader
        type FormatError
            func (e *FormatError) Error() string
        type Load
        type LoadBytes
            func (b LoadBytes) Raw() []byte
        type LoadCmd
            func (i LoadCmd) GoString() string
            func (i LoadCmd) String() string
        type Nlist32
        type Nlist64
        type Regs386
        type RegsAMD64
        type Reloc
        type RelocTypeARM
            func (r RelocTypeARM) GoString() string
            func (i RelocTypeARM) String() string
        type RelocTypeARM64
            func (r RelocTypeARM64) GoString() string
            func (i RelocTypeARM64) String() string
        type RelocTypeGeneric
            func (r RelocTypeGeneric) GoString() string
            func (i RelocTypeGeneric) String() string
        type RelocTypeX86_64
            func (r RelocTypeX86_64) GoString() string
            func (i RelocTypeX86_64) String() string
        type Rpath
        type RpathCmd
        type Section
            func (s *Section) Data() ([]byte, error)
            func (s *Section) Open() io.ReadSeeker
        type Section32
        type Section64
        type SectionHeader
        type Segment
            func (s *Segment) Data() ([]byte, error)
            func (s *Segment) Open() io.ReadSeeker
        type Segment32
        type Segment64
        type SegmentHeader
        type Symbol
        type Symtab
        type SymtabCmd
        type Thread
        type Type
            func (t Type) GoString() string
            func (t Type) String() string

        Package files

        fat.go file.go macho.go reloctype.go reloctype_string.go

        Constants

        const (
            Magic32  uint32 = 0xfeedface
            Magic64  uint32 = 0xfeedfacf
            MagicFat uint32 = 0xcafebabe
        )
        const (
            FlagNoUndefs              uint32 = 0x1
            FlagIncrLink              uint32 = 0x2
            FlagDyldLink              uint32 = 0x4
            FlagBindAtLoad            uint32 = 0x8
            FlagPrebound              uint32 = 0x10
            FlagSplitSegs             uint32 = 0x20
            FlagLazyInit              uint32 = 0x40
            FlagTwoLevel              uint32 = 0x80
            FlagForceFlat             uint32 = 0x100
            FlagNoMultiDefs           uint32 = 0x200
            FlagNoFixPrebinding       uint32 = 0x400
            FlagPrebindable           uint32 = 0x800
            FlagAllModsBound          uint32 = 0x1000
            FlagSubsectionsViaSymbols uint32 = 0x2000
            FlagCanonical             uint32 = 0x4000
            FlagWeakDefines           uint32 = 0x8000
            FlagBindsToWeak           uint32 = 0x10000
            FlagAllowStackExecution   uint32 = 0x20000
            FlagRootSafe              uint32 = 0x40000
            FlagSetuidSafe            uint32 = 0x80000
            FlagNoReexportedDylibs    uint32 = 0x100000
            FlagPIE                   uint32 = 0x200000
            FlagDeadStrippableDylib   uint32 = 0x400000
            FlagHasTLVDescriptors     uint32 = 0x800000
            FlagNoHeapExecution       uint32 = 0x1000000
            FlagAppExtensionSafe      uint32 = 0x2000000
        )

        Variables

        ErrNotFat is returned from NewFatFile or OpenFat when the file is not a universal binary but may be a thin binary, based on its magic number.

        var ErrNotFat = &FormatError{0, "not a fat Mach-O file", nil}

        type Cpu

        A Cpu is a Mach-O cpu type.

        type Cpu uint32
        const (
            Cpu386   Cpu = 7
            CpuAmd64 Cpu = Cpu386 | cpuArch64
            CpuArm   Cpu = 12
            CpuArm64 Cpu = CpuArm | cpuArch64
            CpuPpc   Cpu = 18
            CpuPpc64 Cpu = CpuPpc | cpuArch64
        )

        func (Cpu) GoString

        func (i Cpu) GoString() string

        func (Cpu) String

        func (i Cpu) String() string

        type Dylib

        A Dylib represents a Mach-O load dynamic library command.

        type Dylib struct {
            LoadBytes
            Name           string
            Time           uint32
            CurrentVersion uint32
            CompatVersion  uint32
        }
        

        type DylibCmd

        A DylibCmd is a Mach-O load dynamic library command.

        type DylibCmd struct {
            Cmd            LoadCmd
            Len            uint32
            Name           uint32
            Time           uint32
            CurrentVersion uint32
            CompatVersion  uint32
        }
        

        type Dysymtab

        A Dysymtab represents a Mach-O dynamic symbol table command.

        type Dysymtab struct {
            LoadBytes
            DysymtabCmd
            IndirectSyms []uint32 // indices into Symtab.Syms
        }
        

        type DysymtabCmd

        A DysymtabCmd is a Mach-O dynamic symbol table command.

        type DysymtabCmd struct {
            Cmd            LoadCmd
            Len            uint32
            Ilocalsym      uint32
            Nlocalsym      uint32
            Iextdefsym     uint32
            Nextdefsym     uint32
            Iundefsym      uint32
            Nundefsym      uint32
            Tocoffset      uint32
            Ntoc           uint32
            Modtaboff      uint32
            Nmodtab        uint32
            Extrefsymoff   uint32
            Nextrefsyms    uint32
            Indirectsymoff uint32
            Nindirectsyms  uint32
            Extreloff      uint32
            Nextrel        uint32
            Locreloff      uint32
            Nlocrel        uint32
        }
        

        type FatArch

        A FatArch is a Mach-O File inside a FatFile.

        type FatArch struct {
            FatArchHeader
            *File
        }
        

        type FatArchHeader

        A FatArchHeader represents a fat header for a specific image architecture.

        type FatArchHeader struct {
            Cpu    Cpu
            SubCpu uint32
            Offset uint32
            Size   uint32
            Align  uint32
        }
        

        type FatFile

        A FatFile is a Mach-O universal binary that contains at least one architecture.

        type FatFile struct {
            Magic  uint32
            Arches []FatArch
            // contains filtered or unexported fields
        }
        

        func NewFatFile

        func NewFatFile(r io.ReaderAt) (*FatFile, error)

        NewFatFile creates a new FatFile for accessing all the Mach-O images in a universal binary. The Mach-O binary is expected to start at position 0 in the ReaderAt.

        func OpenFat

        func OpenFat(name string) (*FatFile, error)

        OpenFat opens the named file using os.Open and prepares it for use as a Mach-O universal binary.

        func (*FatFile) Close

        func (ff *FatFile) Close() error

        type File

        A File represents an open Mach-O file.

        type File struct {
            FileHeader
            ByteOrder binary.ByteOrder
            Loads     []Load
            Sections  []*Section
        
            Symtab   *Symtab
            Dysymtab *Dysymtab
            // contains filtered or unexported fields
        }
        

        func NewFile

        func NewFile(r io.ReaderAt) (*File, error)

        NewFile creates a new File for accessing a Mach-O binary in an underlying reader. The Mach-O binary is expected to start at position 0 in the ReaderAt.

        func Open

        func Open(name string) (*File, error)

        Open opens the named file using os.Open and prepares it for use as a Mach-O binary.

        func (*File) Close

        func (f *File) Close() error

        Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

        func (*File) DWARF

        func (f *File) DWARF() (*dwarf.Data, error)

        DWARF returns the DWARF debug information for the Mach-O file.

        func (*File) ImportedLibraries

        func (f *File) ImportedLibraries() ([]string, error)

        ImportedLibraries returns the paths of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.

        func (*File) ImportedSymbols

        func (f *File) ImportedSymbols() ([]string, error)

        ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time.

        func (*File) Section

        func (f *File) Section(name string) *Section

        Section returns the first section with the given name, or nil if no such section exists.

        func (*File) Segment

        func (f *File) Segment(name string) *Segment

        Segment returns the first Segment with the given name, or nil if no such segment exists.

        type FileHeader

        A FileHeader represents a Mach-O file header.

        type FileHeader struct {
            Magic  uint32
            Cpu    Cpu
            SubCpu uint32
            Type   Type
            Ncmd   uint32
            Cmdsz  uint32
            Flags  uint32
        }
        

        type FormatError

        FormatError is returned by some operations if the data does not have the correct format for an object file.

        type FormatError struct {
            // contains filtered or unexported fields
        }
        

        func (*FormatError) Error

        func (e *FormatError) Error() string

        type Load

        A Load represents any Mach-O load command.

        type Load interface {
            Raw() []byte
        }

        type LoadBytes

        A LoadBytes is the uninterpreted bytes of a Mach-O load command.

        type LoadBytes []byte

        func (LoadBytes) Raw

        func (b LoadBytes) Raw() []byte

        type LoadCmd

        A LoadCmd is a Mach-O load command.

        type LoadCmd uint32
        const (
            LoadCmdSegment    LoadCmd = 0x1
            LoadCmdSymtab     LoadCmd = 0x2
            LoadCmdThread     LoadCmd = 0x4
            LoadCmdUnixThread LoadCmd = 0x5 // thread+stack
            LoadCmdDysymtab   LoadCmd = 0xb
            LoadCmdDylib      LoadCmd = 0xc // load dylib command
            LoadCmdDylinker   LoadCmd = 0xf // id dylinker command (not load dylinker command)
            LoadCmdSegment64  LoadCmd = 0x19
            LoadCmdRpath      LoadCmd = 0x8000001c
        )

        func (LoadCmd) GoString

        func (i LoadCmd) GoString() string

        func (LoadCmd) String

        func (i LoadCmd) String() string

        type Nlist32

        An Nlist32 is a Mach-O 32-bit symbol table entry.

        type Nlist32 struct {
            Name  uint32
            Type  uint8
            Sect  uint8
            Desc  uint16
            Value uint32
        }
        

        type Nlist64

        An Nlist64 is a Mach-O 64-bit symbol table entry.

        type Nlist64 struct {
            Name  uint32
            Type  uint8
            Sect  uint8
            Desc  uint16
            Value uint64
        }
        

        type Regs386

        Regs386 is the Mach-O 386 register structure.

        type Regs386 struct {
            AX    uint32
            BX    uint32
            CX    uint32
            DX    uint32
            DI    uint32
            SI    uint32
            BP    uint32
            SP    uint32
            SS    uint32
            FLAGS uint32
            IP    uint32
            CS    uint32
            DS    uint32
            ES    uint32
            FS    uint32
            GS    uint32
        }
        

        type RegsAMD64

        RegsAMD64 is the Mach-O AMD64 register structure.

        type RegsAMD64 struct {
            AX    uint64
            BX    uint64
            CX    uint64
            DX    uint64
            DI    uint64
            SI    uint64
            BP    uint64
            SP    uint64
            R8    uint64
            R9    uint64
            R10   uint64
            R11   uint64
            R12   uint64
            R13   uint64
            R14   uint64
            R15   uint64
            IP    uint64
            FLAGS uint64
            CS    uint64
            FS    uint64
            GS    uint64
        }
        

        type Reloc

        A Reloc represents a Mach-O relocation.

        type Reloc struct {
            Addr  uint32
            Value uint32
            // when Scattered == false && Extern == true, Value is the symbol number.
            // when Scattered == false && Extern == false, Value is the section number.
            // when Scattered == true, Value is the value that this reloc refers to.
            Type      uint8
            Len       uint8 // 0=byte, 1=word, 2=long, 3=quad
            Pcrel     bool
            Extern    bool // valid if Scattered == false
            Scattered bool
        }
        

        type RelocTypeARM

        type RelocTypeARM int
        const (
            ARM_RELOC_VANILLA        RelocTypeARM = 0
            ARM_RELOC_PAIR           RelocTypeARM = 1
            ARM_RELOC_SECTDIFF       RelocTypeARM = 2
            ARM_RELOC_LOCAL_SECTDIFF RelocTypeARM = 3
            ARM_RELOC_PB_LA_PTR      RelocTypeARM = 4
            ARM_RELOC_BR24           RelocTypeARM = 5
            ARM_THUMB_RELOC_BR22     RelocTypeARM = 6
            ARM_THUMB_32BIT_BRANCH   RelocTypeARM = 7
            ARM_RELOC_HALF           RelocTypeARM = 8
            ARM_RELOC_HALF_SECTDIFF  RelocTypeARM = 9
        )

        func (RelocTypeARM) GoString

        func (r RelocTypeARM) GoString() string

        func (RelocTypeARM) String

        func (i RelocTypeARM) String() string

        type RelocTypeARM64

        type RelocTypeARM64 int
        const (
            ARM64_RELOC_UNSIGNED            RelocTypeARM64 = 0
            ARM64_RELOC_SUBTRACTOR          RelocTypeARM64 = 1
            ARM64_RELOC_BRANCH26            RelocTypeARM64 = 2
            ARM64_RELOC_PAGE21              RelocTypeARM64 = 3
            ARM64_RELOC_PAGEOFF12           RelocTypeARM64 = 4
            ARM64_RELOC_GOT_LOAD_PAGE21     RelocTypeARM64 = 5
            ARM64_RELOC_GOT_LOAD_PAGEOFF12  RelocTypeARM64 = 6
            ARM64_RELOC_POINTER_TO_GOT      RelocTypeARM64 = 7
            ARM64_RELOC_TLVP_LOAD_PAGE21    RelocTypeARM64 = 8
            ARM64_RELOC_TLVP_LOAD_PAGEOFF12 RelocTypeARM64 = 9
            ARM64_RELOC_ADDEND              RelocTypeARM64 = 10
        )

        func (RelocTypeARM64) GoString

        func (r RelocTypeARM64) GoString() string

        func (RelocTypeARM64) String

        func (i RelocTypeARM64) String() string

        type RelocTypeGeneric

        type RelocTypeGeneric int
        const (
            GENERIC_RELOC_VANILLA        RelocTypeGeneric = 0
            GENERIC_RELOC_PAIR           RelocTypeGeneric = 1
            GENERIC_RELOC_SECTDIFF       RelocTypeGeneric = 2
            GENERIC_RELOC_PB_LA_PTR      RelocTypeGeneric = 3
            GENERIC_RELOC_LOCAL_SECTDIFF RelocTypeGeneric = 4
            GENERIC_RELOC_TLV            RelocTypeGeneric = 5
        )

        func (RelocTypeGeneric) GoString

        func (r RelocTypeGeneric) GoString() string

        func (RelocTypeGeneric) String

        func (i RelocTypeGeneric) String() string

        type RelocTypeX86_64

        type RelocTypeX86_64 int
        const (
            X86_64_RELOC_UNSIGNED   RelocTypeX86_64 = 0
            X86_64_RELOC_SIGNED     RelocTypeX86_64 = 1
            X86_64_RELOC_BRANCH     RelocTypeX86_64 = 2
            X86_64_RELOC_GOT_LOAD   RelocTypeX86_64 = 3
            X86_64_RELOC_GOT        RelocTypeX86_64 = 4
            X86_64_RELOC_SUBTRACTOR RelocTypeX86_64 = 5
            X86_64_RELOC_SIGNED_1   RelocTypeX86_64 = 6
            X86_64_RELOC_SIGNED_2   RelocTypeX86_64 = 7
            X86_64_RELOC_SIGNED_4   RelocTypeX86_64 = 8
            X86_64_RELOC_TLV        RelocTypeX86_64 = 9
        )

        func (RelocTypeX86_64) GoString

        func (r RelocTypeX86_64) GoString() string

        func (RelocTypeX86_64) String

        func (i RelocTypeX86_64) String() string

        type Rpath

        A Rpath represents a Mach-O rpath command.

        type Rpath struct {
            LoadBytes
            Path string
        }
        

        type RpathCmd

        A RpathCmd is a Mach-O rpath command.

        type RpathCmd struct {
            Cmd  LoadCmd
            Len  uint32
            Path uint32
        }
        

        type Section

        type Section struct {
            SectionHeader
            Relocs []Reloc
        
            // Embed ReaderAt for ReadAt method.
            // Do not embed SectionReader directly
            // to avoid having Read and Seek.
            // If a client wants Read and Seek it must use
            // Open() to avoid fighting over the seek offset
            // with other clients.
            io.ReaderAt
            // contains filtered or unexported fields
        }
        

        func (*Section) Data

        func (s *Section) Data() ([]byte, error)

        Data reads and returns the contents of the Mach-O section.

        func (*Section) Open

        func (s *Section) Open() io.ReadSeeker

        Open returns a new ReadSeeker reading the Mach-O section.

        type Section32

        A Section32 is a 32-bit Mach-O section header.

        type Section32 struct {
            Name     [16]byte
            Seg      [16]byte
            Addr     uint32
            Size     uint32
            Offset   uint32
            Align    uint32
            Reloff   uint32
            Nreloc   uint32
            Flags    uint32
            Reserve1 uint32
            Reserve2 uint32
        }
        

        type Section64

        A Section64 is a 64-bit Mach-O section header.

        type Section64 struct {
            Name     [16]byte
            Seg      [16]byte
            Addr     uint64
            Size     uint64
            Offset   uint32
            Align    uint32
            Reloff   uint32
            Nreloc   uint32
            Flags    uint32
            Reserve1 uint32
            Reserve2 uint32
            Reserve3 uint32
        }
        

        type SectionHeader

        type SectionHeader struct {
            Name   string
            Seg    string
            Addr   uint64
            Size   uint64
            Offset uint32
            Align  uint32
            Reloff uint32
            Nreloc uint32
            Flags  uint32
        }
        

        type Segment

        A Segment represents a Mach-O 32-bit or 64-bit load segment command.

        type Segment struct {
            LoadBytes
            SegmentHeader
        
            // Embed ReaderAt for ReadAt method.
            // Do not embed SectionReader directly
            // to avoid having Read and Seek.
            // If a client wants Read and Seek it must use
            // Open() to avoid fighting over the seek offset
            // with other clients.
            io.ReaderAt
            // contains filtered or unexported fields
        }
        

        func (*Segment) Data

        func (s *Segment) Data() ([]byte, error)

        Data reads and returns the contents of the segment.

        func (*Segment) Open

        func (s *Segment) Open() io.ReadSeeker

        Open returns a new ReadSeeker reading the segment.

        type Segment32

        A Segment32 is a 32-bit Mach-O segment load command.

        type Segment32 struct {
            Cmd     LoadCmd
            Len     uint32
            Name    [16]byte
            Addr    uint32
            Memsz   uint32
            Offset  uint32
            Filesz  uint32
            Maxprot uint32
            Prot    uint32
            Nsect   uint32
            Flag    uint32
        }
        

        type Segment64

        A Segment64 is a 64-bit Mach-O segment load command.

        type Segment64 struct {
            Cmd     LoadCmd
            Len     uint32
            Name    [16]byte
            Addr    uint64
            Memsz   uint64
            Offset  uint64
            Filesz  uint64
            Maxprot uint32
            Prot    uint32
            Nsect   uint32
            Flag    uint32
        }
        

        type SegmentHeader

        A SegmentHeader is the header for a Mach-O 32-bit or 64-bit load segment command.

        type SegmentHeader struct {
            Cmd     LoadCmd
            Len     uint32
            Name    string
            Addr    uint64
            Memsz   uint64
            Offset  uint64
            Filesz  uint64
            Maxprot uint32
            Prot    uint32
            Nsect   uint32
            Flag    uint32
        }
        

        type Symbol

        A Symbol is a Mach-O 32-bit or 64-bit symbol table entry.

        type Symbol struct {
            Name  string
            Type  uint8
            Sect  uint8
            Desc  uint16
            Value uint64
        }
        

        type Symtab

        A Symtab represents a Mach-O symbol table command.

        type Symtab struct {
            LoadBytes
            SymtabCmd
            Syms []Symbol
        }
        

        type SymtabCmd

        A SymtabCmd is a Mach-O symbol table command.

        type SymtabCmd struct {
            Cmd     LoadCmd
            Len     uint32
            Symoff  uint32
            Nsyms   uint32
            Stroff  uint32
            Strsize uint32
        }
        

        type Thread

        A Thread is a Mach-O thread state command.

        type Thread struct {
            Cmd  LoadCmd
            Len  uint32
            Type uint32
            Data []uint32
        }
        

        type Type

        A Type is the Mach-O file type, e.g. an object file, executable, or dynamic library.

        type Type uint32
        const (
            TypeObj    Type = 1
            TypeExec   Type = 2
            TypeDylib  Type = 6
            TypeBundle Type = 8
        )

        func (Type) GoString

        func (t Type) GoString() string

        func (Type) String

        func (t Type) String() string
        pe - Go Documentation Server
        ...

        Package pe

        import "debug/pe"
        Overview
        Index

        Overview ▾

        Package pe implements access to PE (Microsoft Windows Portable Executable) files.

        Security

        This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

        Constants

        const (
            IMAGE_FILE_MACHINE_UNKNOWN     = 0x0
            IMAGE_FILE_MACHINE_AM33        = 0x1d3
            IMAGE_FILE_MACHINE_AMD64       = 0x8664
            IMAGE_FILE_MACHINE_ARM         = 0x1c0
            IMAGE_FILE_MACHINE_ARMNT       = 0x1c4
            IMAGE_FILE_MACHINE_ARM64       = 0xaa64
            IMAGE_FILE_MACHINE_EBC         = 0xebc
            IMAGE_FILE_MACHINE_I386        = 0x14c
            IMAGE_FILE_MACHINE_IA64        = 0x200
            IMAGE_FILE_MACHINE_LOONGARCH32 = 0x6232
            IMAGE_FILE_MACHINE_LOONGARCH64 = 0x6264
            IMAGE_FILE_MACHINE_M32R        = 0x9041
            IMAGE_FILE_MACHINE_MIPS16      = 0x266
            IMAGE_FILE_MACHINE_MIPSFPU     = 0x366
            IMAGE_FILE_MACHINE_MIPSFPU16   = 0x466
            IMAGE_FILE_MACHINE_POWERPC     = 0x1f0
            IMAGE_FILE_MACHINE_POWERPCFP   = 0x1f1
            IMAGE_FILE_MACHINE_R4000       = 0x166
            IMAGE_FILE_MACHINE_SH3         = 0x1a2
            IMAGE_FILE_MACHINE_SH3DSP      = 0x1a3
            IMAGE_FILE_MACHINE_SH4         = 0x1a6
            IMAGE_FILE_MACHINE_SH5         = 0x1a8
            IMAGE_FILE_MACHINE_THUMB       = 0x1c2
            IMAGE_FILE_MACHINE_WCEMIPSV2   = 0x169
            IMAGE_FILE_MACHINE_RISCV32     = 0x5032
            IMAGE_FILE_MACHINE_RISCV64     = 0x5064
            IMAGE_FILE_MACHINE_RISCV128    = 0x5128
        )

        IMAGE_DIRECTORY_ENTRY constants

        const (
            IMAGE_DIRECTORY_ENTRY_EXPORT         = 0
            IMAGE_DIRECTORY_ENTRY_IMPORT         = 1
            IMAGE_DIRECTORY_ENTRY_RESOURCE       = 2
            IMAGE_DIRECTORY_ENTRY_EXCEPTION      = 3
            IMAGE_DIRECTORY_ENTRY_SECURITY       = 4
            IMAGE_DIRECTORY_ENTRY_BASERELOC      = 5
            IMAGE_DIRECTORY_ENTRY_DEBUG          = 6
            IMAGE_DIRECTORY_ENTRY_ARCHITECTURE   = 7
            IMAGE_DIRECTORY_ENTRY_GLOBALPTR      = 8
            IMAGE_DIRECTORY_ENTRY_TLS            = 9
            IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG    = 10
            IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT   = 11
            IMAGE_DIRECTORY_ENTRY_IAT            = 12
            IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT   = 13
            IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14
        )

        Values of IMAGE_FILE_HEADER.Characteristics. These can be combined together.

        const (
            IMAGE_FILE_RELOCS_STRIPPED         = 0x0001
            IMAGE_FILE_EXECUTABLE_IMAGE        = 0x0002
            IMAGE_FILE_LINE_NUMS_STRIPPED      = 0x0004
            IMAGE_FILE_LOCAL_SYMS_STRIPPED     = 0x0008
            IMAGE_FILE_AGGRESIVE_WS_TRIM       = 0x0010
            IMAGE_FILE_LARGE_ADDRESS_AWARE     = 0x0020
            IMAGE_FILE_BYTES_REVERSED_LO       = 0x0080
            IMAGE_FILE_32BIT_MACHINE           = 0x0100
            IMAGE_FILE_DEBUG_STRIPPED          = 0x0200
            IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400
            IMAGE_FILE_NET_RUN_FROM_SWAP       = 0x0800
            IMAGE_FILE_SYSTEM                  = 0x1000
            IMAGE_FILE_DLL                     = 0x2000
            IMAGE_FILE_UP_SYSTEM_ONLY          = 0x4000
            IMAGE_FILE_BYTES_REVERSED_HI       = 0x8000
        )

        OptionalHeader64.Subsystem and OptionalHeader32.Subsystem values.

        const (
            IMAGE_SUBSYSTEM_UNKNOWN                  = 0
            IMAGE_SUBSYSTEM_NATIVE                   = 1
            IMAGE_SUBSYSTEM_WINDOWS_GUI              = 2
            IMAGE_SUBSYSTEM_WINDOWS_CUI              = 3
            IMAGE_SUBSYSTEM_OS2_CUI                  = 5
            IMAGE_SUBSYSTEM_POSIX_CUI                = 7
            IMAGE_SUBSYSTEM_NATIVE_WINDOWS           = 8
            IMAGE_SUBSYSTEM_WINDOWS_CE_GUI           = 9
            IMAGE_SUBSYSTEM_EFI_APPLICATION          = 10
            IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER  = 11
            IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER       = 12
            IMAGE_SUBSYSTEM_EFI_ROM                  = 13
            IMAGE_SUBSYSTEM_XBOX                     = 14
            IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION = 16
        )

        OptionalHeader64.DllCharacteristics and OptionalHeader32.DllCharacteristics values. These can be combined together.

        const (
            IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA       = 0x0020
            IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE          = 0x0040
            IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY       = 0x0080
            IMAGE_DLLCHARACTERISTICS_NX_COMPAT             = 0x0100
            IMAGE_DLLCHARACTERISTICS_NO_ISOLATION          = 0x0200
            IMAGE_DLLCHARACTERISTICS_NO_SEH                = 0x0400
            IMAGE_DLLCHARACTERISTICS_NO_BIND               = 0x0800
            IMAGE_DLLCHARACTERISTICS_APPCONTAINER          = 0x1000
            IMAGE_DLLCHARACTERISTICS_WDM_DRIVER            = 0x2000
            IMAGE_DLLCHARACTERISTICS_GUARD_CF              = 0x4000
            IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000
        )

        Section characteristics flags.

        const (
            IMAGE_SCN_CNT_CODE               = 0x00000020
            IMAGE_SCN_CNT_INITIALIZED_DATA   = 0x00000040
            IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080
            IMAGE_SCN_LNK_COMDAT             = 0x00001000
            IMAGE_SCN_MEM_DISCARDABLE        = 0x02000000
            IMAGE_SCN_MEM_EXECUTE            = 0x20000000
            IMAGE_SCN_MEM_READ               = 0x40000000
            IMAGE_SCN_MEM_WRITE              = 0x80000000
        )

        These constants make up the possible values for the 'Selection' field in an AuxFormat5.

        const (
            IMAGE_COMDAT_SELECT_NODUPLICATES = 1
            IMAGE_COMDAT_SELECT_ANY          = 2
            IMAGE_COMDAT_SELECT_SAME_SIZE    = 3
            IMAGE_COMDAT_SELECT_EXACT_MATCH  = 4
            IMAGE_COMDAT_SELECT_ASSOCIATIVE  = 5
            IMAGE_COMDAT_SELECT_LARGEST      = 6
        )
        const COFFSymbolSize = 18

        type COFFSymbol

        COFFSymbol represents single COFF symbol table record.

        type COFFSymbol struct {
            Name               [8]uint8
            Value              uint32
            SectionNumber      int16
            Type               uint16
            StorageClass       uint8
            NumberOfAuxSymbols uint8
        }
        

        func (*COFFSymbol) FullName

        func (sym *COFFSymbol) FullName(st StringTable) (string, error)

        FullName finds real name of symbol sym. Normally name is stored in sym.Name, but if it is longer then 8 characters, it is stored in COFF string table st instead.

        type COFFSymbolAuxFormat5

        COFFSymbolAuxFormat5 describes the expected form of an aux symbol attached to a section definition symbol. The PE format defines a number of different aux symbol formats: format 1 for function definitions, format 2 for .be and .ef symbols, and so on. Format 5 holds extra info associated with a section definition, including number of relocations + line numbers, as well as COMDAT info. See https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-format-5-section-definitions for more on what's going on here.

        type COFFSymbolAuxFormat5 struct {
            Size           uint32
            NumRelocs      uint16
            NumLineNumbers uint16
            Checksum       uint32
            SecNum         uint16
            Selection      uint8
            // contains filtered or unexported fields
        }
        

        type DataDirectory

        type DataDirectory struct {
            VirtualAddress uint32
            Size           uint32
        }
        

        type File

        A File represents an open PE file.

        type File struct {
            FileHeader
            OptionalHeader any // of type *OptionalHeader32 or *OptionalHeader64
            Sections       []*Section
            Symbols        []*Symbol    // COFF symbols with auxiliary symbol records removed
            COFFSymbols    []COFFSymbol // all COFF symbols (including auxiliary symbol records)
            StringTable    StringTable
            // contains filtered or unexported fields
        }
        

        func NewFile

        func NewFile(r io.ReaderAt) (*File, error)

        NewFile creates a new File for accessing a PE binary in an underlying reader.

        func Open

        func Open(name string) (*File, error)

        Open opens the named file using os.Open and prepares it for use as a PE binary.

        func (*File) COFFSymbolReadSectionDefAux

        func (f *File) COFFSymbolReadSectionDefAux(idx int) (*COFFSymbolAuxFormat5, error)

        COFFSymbolReadSectionDefAux returns a blob of auxiliary information (including COMDAT info) for a section definition symbol. Here 'idx' is the index of a section symbol in the main COFFSymbol array for the File. Return value is a pointer to the appropriate aux symbol struct. For more info, see:

        auxiliary symbols: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-symbol-records COMDAT sections: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#comdat-sections-object-only auxiliary info for section definitions: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#auxiliary-format-5-section-definitions

        func (*File) Close

        func (f *File) Close() error

        Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

        func (*File) DWARF

        func (f *File) DWARF() (*dwarf.Data, error)

        func (*File) ImportedLibraries

        func (f *File) ImportedLibraries() ([]string, error)

        ImportedLibraries returns the names of all libraries referred to by the binary f that are expected to be linked with the binary at dynamic link time.

        func (*File) ImportedSymbols

        func (f *File) ImportedSymbols() ([]string, error)

        ImportedSymbols returns the names of all symbols referred to by the binary f that are expected to be satisfied by other libraries at dynamic load time. It does not return weak symbols.

        func (*File) Section

        func (f *File) Section(name string) *Section

        Section returns the first section with the given name, or nil if no such section exists.

        type FileHeader

        type FileHeader struct {
            Machine              uint16
            NumberOfSections     uint16
            TimeDateStamp        uint32
            PointerToSymbolTable uint32
            NumberOfSymbols      uint32
            SizeOfOptionalHeader uint16
            Characteristics      uint16
        }
        

        type FormatError

        FormatError is unused. The type is retained for compatibility.

        type FormatError struct {
        }
        

        func (*FormatError) Error

        func (e *FormatError) Error() string

        type ImportDirectory

        type ImportDirectory struct {
            OriginalFirstThunk uint32
            TimeDateStamp      uint32
            ForwarderChain     uint32
            Name               uint32
            FirstThunk         uint32
            // contains filtered or unexported fields
        }
        

        type OptionalHeader32

        type OptionalHeader32 struct {
            Magic                       uint16
            MajorLinkerVersion          uint8
            MinorLinkerVersion          uint8
            SizeOfCode                  uint32
            SizeOfInitializedData       uint32
            SizeOfUninitializedData     uint32
            AddressOfEntryPoint         uint32
            BaseOfCode                  uint32
            BaseOfData                  uint32
            ImageBase                   uint32
            SectionAlignment            uint32
            FileAlignment               uint32
            MajorOperatingSystemVersion uint16
            MinorOperatingSystemVersion uint16
            MajorImageVersion           uint16
            MinorImageVersion           uint16
            MajorSubsystemVersion       uint16
            MinorSubsystemVersion       uint16
            Win32VersionValue           uint32
            SizeOfImage                 uint32
            SizeOfHeaders               uint32
            CheckSum                    uint32
            Subsystem                   uint16
            DllCharacteristics          uint16
            SizeOfStackReserve          uint32
            SizeOfStackCommit           uint32
            SizeOfHeapReserve           uint32
            SizeOfHeapCommit            uint32
            LoaderFlags                 uint32
            NumberOfRvaAndSizes         uint32
            DataDirectory               [16]DataDirectory
        }
        

        type OptionalHeader64

        type OptionalHeader64 struct {
            Magic                       uint16
            MajorLinkerVersion          uint8
            MinorLinkerVersion          uint8
            SizeOfCode                  uint32
            SizeOfInitializedData       uint32
            SizeOfUninitializedData     uint32
            AddressOfEntryPoint         uint32
            BaseOfCode                  uint32
            ImageBase                   uint64
            SectionAlignment            uint32
            FileAlignment               uint32
            MajorOperatingSystemVersion uint16
            MinorOperatingSystemVersion uint16
            MajorImageVersion           uint16
            MinorImageVersion           uint16
            MajorSubsystemVersion       uint16
            MinorSubsystemVersion       uint16
            Win32VersionValue           uint32
            SizeOfImage                 uint32
            SizeOfHeaders               uint32
            CheckSum                    uint32
            Subsystem                   uint16
            DllCharacteristics          uint16
            SizeOfStackReserve          uint64
            SizeOfStackCommit           uint64
            SizeOfHeapReserve           uint64
            SizeOfHeapCommit            uint64
            LoaderFlags                 uint32
            NumberOfRvaAndSizes         uint32
            DataDirectory               [16]DataDirectory
        }
        

        type Reloc

        Reloc represents a PE COFF relocation. Each section contains its own relocation list.

        type Reloc struct {
            VirtualAddress   uint32
            SymbolTableIndex uint32
            Type             uint16
        }
        

        type Section

        Section provides access to PE COFF section.

        type Section struct {
            SectionHeader
            Relocs []Reloc
        
            // Embed ReaderAt for ReadAt method.
            // Do not embed SectionReader directly
            // to avoid having Read and Seek.
            // If a client wants Read and Seek it must use
            // Open() to avoid fighting over the seek offset
            // with other clients.
            io.ReaderAt
            // contains filtered or unexported fields
        }
        

        func (*Section) Data

        func (s *Section) Data() ([]byte, error)

        Data reads and returns the contents of the PE section s.

        If s.Offset is 0, the section has no contents, and Data will always return a non-nil error.

        func (*Section) Open

        func (s *Section) Open() io.ReadSeeker

        Open returns a new ReadSeeker reading the PE section s.

        If s.Offset is 0, the section has no contents, and all calls to the returned reader will return a non-nil error.

        type SectionHeader

        SectionHeader is similar to SectionHeader32 with Name field replaced by Go string.

        type SectionHeader struct {
            Name                 string
            VirtualSize          uint32
            VirtualAddress       uint32
            Size                 uint32
            Offset               uint32
            PointerToRelocations uint32
            PointerToLineNumbers uint32
            NumberOfRelocations  uint16
            NumberOfLineNumbers  uint16
            Characteristics      uint32
        }
        

        type SectionHeader32

        SectionHeader32 represents real PE COFF section header.

        type SectionHeader32 struct {
            Name                 [8]uint8
            VirtualSize          uint32
            VirtualAddress       uint32
            SizeOfRawData        uint32
            PointerToRawData     uint32
            PointerToRelocations uint32
            PointerToLineNumbers uint32
            NumberOfRelocations  uint16
            NumberOfLineNumbers  uint16
            Characteristics      uint32
        }
        

        type StringTable

        StringTable is a COFF string table.

        type StringTable []byte

        func (StringTable) String

        func (st StringTable) String(start uint32) (string, error)

        String extracts string from COFF string table st at offset start.

        type Symbol

        Symbol is similar to COFFSymbol with Name field replaced by Go string. Symbol also does not have NumberOfAuxSymbols.

        type Symbol struct {
            Name          string
            Value         uint32
            SectionNumber int16
            Type          uint16
            StorageClass  uint8
        }
        
        plan9obj - Go Documentation Server
        ...

        Package plan9obj

        import "debug/plan9obj"
        Overview
        Index

        Overview ▾

        Package plan9obj implements access to Plan 9 a.out object files.

        Security

        This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, only basic validation is done when parsing object files. As such, care should be taken when parsing untrusted inputs, as parsing malformed files may consume significant resources, or cause panics.

        Constants

        const (
            Magic64 = 0x8000 // 64-bit expanded header
        
            Magic386   = (4*11+0)*11 + 7
            MagicAMD64 = (4*26+0)*26 + 7 + Magic64
            MagicARM   = (4*20+0)*20 + 7
        )

        Variables

        ErrNoSymbols is returned by File.Symbols if there is no such section in the File.

        var ErrNoSymbols = errors.New("no symbol section")

        type File

        A File represents an open Plan 9 a.out file.

        type File struct {
            FileHeader
            Sections []*Section
            // contains filtered or unexported fields
        }
        

        func NewFile

        func NewFile(r io.ReaderAt) (*File, error)

        NewFile creates a new File for accessing a Plan 9 binary in an underlying reader. The Plan 9 binary is expected to start at position 0 in the ReaderAt.

        func Open

        func Open(name string) (*File, error)

        Open opens the named file using os.Open and prepares it for use as a Plan 9 a.out binary.

        func (*File) Close

        func (f *File) Close() error

        Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

        func (*File) Section

        func (f *File) Section(name string) *Section

        Section returns a section with the given name, or nil if no such section exists.

        func (*File) Symbols

        func (f *File) Symbols() ([]Sym, error)

        Symbols returns the symbol table for f.

        type FileHeader

        A FileHeader represents a Plan 9 a.out file header.

        type FileHeader struct {
            Magic       uint32
            Bss         uint32
            Entry       uint64
            PtrSize     int
            LoadAddress uint64
            HdrSize     uint64
        }
        

        type Section

        A Section represents a single section in a Plan 9 a.out file.

        type Section struct {
            SectionHeader
        
            // Embed ReaderAt for ReadAt method.
            // Do not embed SectionReader directly
            // to avoid having Read and Seek.
            // If a client wants Read and Seek it must use
            // Open() to avoid fighting over the seek offset
            // with other clients.
            io.ReaderAt
            // contains filtered or unexported fields
        }
        

        func (*Section) Data

        func (s *Section) Data() ([]byte, error)

        Data reads and returns the contents of the Plan 9 a.out section.

        func (*Section) Open

        func (s *Section) Open() io.ReadSeeker

        Open returns a new ReadSeeker reading the Plan 9 a.out section.

        type SectionHeader

        A SectionHeader represents a single Plan 9 a.out section header. This structure doesn't exist on-disk, but eases navigation through the object file.

        type SectionHeader struct {
            Name   string
            Size   uint32
            Offset uint32
        }
        

        type Sym

        A Symbol represents an entry in a Plan 9 a.out symbol table section.

        type Sym struct {
            Value uint64
            Type  rune
            Name  string
        }
        
        embed - Go Documentation Server
        ...

        Package embed

        import "embed"
        Overview
        Index
        Examples

        Overview ▾

        Package embed provides access to files embedded in the running Go program.

        Go source files that import "embed" can use the //go:embed directive to initialize a variable of type string, []byte, or FS with the contents of files read from the package directory or subdirectories at compile time.

        For example, here are three ways to embed a file named hello.txt and then print its contents at run time.

        Embedding one file into a string:

        import _ "embed"
        
        //go:embed hello.txt
        var s string
        print(s)
        

        Embedding one file into a slice of bytes:

        import _ "embed"
        
        //go:embed hello.txt
        var b []byte
        print(string(b))
        

        Embedded one or more files into a file system:

        import "embed"
        
        //go:embed hello.txt
        var f embed.FS
        data, _ := f.ReadFile("hello.txt")
        print(string(data))
        

        Directives

        A //go:embed directive above a variable declaration specifies which files to embed, using one or more path.Match patterns.

        The directive must immediately precede a line containing the declaration of a single variable. Only blank lines and ‘//’ line comments are permitted between the directive and the declaration.

        The type of the variable must be a string type, or a slice of a byte type, or FS (or an alias of FS).

        For example:

        package server
        
        import "embed"
        
        // content holds our static web server content.
        //go:embed image/* template/*
        //go:embed html/index.html
        var content embed.FS
        

        The Go build system will recognize the directives and arrange for the declared variable (in the example above, content) to be populated with the matching files from the file system.

        The //go:embed directive accepts multiple space-separated patterns for brevity, but it can also be repeated, to avoid very long lines when there are many patterns. The patterns are interpreted relative to the package directory containing the source file. The path separator is a forward slash, even on Windows systems. Patterns may not contain ‘.’ or ‘..’ or empty path elements, nor may they begin or end with a slash. To match everything in the current directory, use ‘*’ instead of ‘.’. To allow for naming files with spaces in their names, patterns can be written as Go double-quoted or back-quoted string literals.

        If a pattern names a directory, all files in the subtree rooted at that directory are embedded (recursively), except that files with names beginning with ‘.’ or ‘_’ are excluded. So the variable in the above example is almost equivalent to:

        // content is our static web server content.
        //go:embed image template html/index.html
        var content embed.FS
        

        The difference is that ‘image/*’ embeds ‘image/.tempfile’ while ‘image’ does not. Neither embeds ‘image/dir/.tempfile’.

        If a pattern begins with the prefix ‘all:’, then the rule for walking directories is changed to include those files beginning with ‘.’ or ‘_’. For example, ‘all:image’ embeds both ‘image/.tempfile’ and ‘image/dir/.tempfile’.

        The //go:embed directive can be used with both exported and unexported variables, depending on whether the package wants to make the data available to other packages. It can only be used with variables at package scope, not with local variables.

        Patterns must not match files outside the package's module, such as ‘.git/*’ or symbolic links. Patterns must not match files whose names include the special punctuation characters " * < > ? ` ' | / \ and :. Matches for empty directories are ignored. After that, each pattern in a //go:embed line must match at least one file or non-empty directory.

        If any patterns are invalid or have invalid matches, the build will fail.

        Strings and Bytes

        The //go:embed line for a variable of type string or []byte can have only a single pattern, and that pattern can match only a single file. The string or []byte is initialized with the contents of that file.

        The //go:embed directive requires importing "embed", even when using a string or []byte. In source files that don't refer to embed.FS, use a blank import (import _ "embed").

        File Systems

        For embedding a single file, a variable of type string or []byte is often best. The FS type enables embedding a tree of files, such as a directory of static web server content, as in the example above.

        FS implements the io/fs package's FS interface, so it can be used with any package that understands file systems, including net/http, text/template, and html/template.

        For example, given the content variable in the example above, we can write:

        http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(content))))
        
        template.ParseFS(content, "*.tmpl")
        

        Tools

        To support tools that analyze Go packages, the patterns found in //go:embed lines are available in “go list” output. See the EmbedPatterns, TestEmbedPatterns, and XTestEmbedPatterns fields in the “go help list” output.

        Example

        Code:

        package embed_test
        
        import (
            "embed"
            "log"
            "net/http"
        )
        
        //go:embed internal/embedtest/testdata/*.txt
        var content embed.FS
        
        func Example() {
            mux := http.NewServeMux()
            mux.Handle("/", http.FileServer(http.FS(content)))
            err := http.ListenAndServe(":8080", mux)
            if err != nil {
                log.Fatal(err)
            }
        }
        

        type FS

        An FS is a read-only collection of files, usually initialized with a //go:embed directive. When declared without a //go:embed directive, an FS is an empty file system.

        An FS is a read-only value, so it is safe to use from multiple goroutines simultaneously and also safe to assign values of type FS to each other.

        FS implements fs.FS, so it can be used with any package that understands file system interfaces, including net/http, text/template, and html/template.

        See the package documentation for more details about initializing an FS.

        type FS struct {
            // contains filtered or unexported fields
        }
        

        func (FS) Open

        func (f FS) Open(name string) (fs.File, error)

        Open opens the named file for reading and returns it as an fs.File.

        The returned file implements io.Seeker and io.ReaderAt when the file is not a directory.

        func (FS) ReadDir

        func (f FS) ReadDir(name string) ([]fs.DirEntry, error)

        ReadDir reads and returns the entire named directory.

        func (FS) ReadFile

        func (f FS) ReadFile(name string) ([]byte, error)

        ReadFile reads and returns the content of the named file.

        encoding - Go Documentation Server
        ...

        Package encoding

        import "encoding"
        Overview
        Index
        Subdirectories

        Overview ▾

        Package encoding defines interfaces shared by other packages that convert data to and from byte-level and textual representations. Packages that check for these interfaces include encoding/gob, encoding/json, and encoding/xml. As a result, implementing an interface once can make a type useful in multiple encodings. Standard types that implement these interfaces include time.Time and net.IP. The interfaces come in pairs that produce and consume encoded data.

        Adding encoding/decoding methods to existing types may constitute a breaking change, as they can be used for serialization in communicating with programs written with different library versions. The policy for packages maintained by the Go project is to only allow the addition of marshaling functions if no existing, reasonable marshaling exists.

        type BinaryMarshaler

        BinaryMarshaler is the interface implemented by an object that can marshal itself into a binary form.

        MarshalBinary encodes the receiver into a binary form and returns the result.

        type BinaryMarshaler interface {
            MarshalBinary() (data []byte, err error)
        }

        type BinaryUnmarshaler

        BinaryUnmarshaler is the interface implemented by an object that can unmarshal a binary representation of itself.

        UnmarshalBinary must be able to decode the form generated by MarshalBinary. UnmarshalBinary must copy the data if it wishes to retain the data after returning.

        type BinaryUnmarshaler interface {
            UnmarshalBinary(data []byte) error
        }

        type TextMarshaler

        TextMarshaler is the interface implemented by an object that can marshal itself into a textual form.

        MarshalText encodes the receiver into UTF-8-encoded text and returns the result.

        type TextMarshaler interface {
            MarshalText() (text []byte, err error)
        }

        type TextUnmarshaler

        TextUnmarshaler is the interface implemented by an object that can unmarshal a textual representation of itself.

        UnmarshalText must be able to decode the form generated by MarshalText. UnmarshalText must copy the text if it wishes to retain the text after returning.

        type TextUnmarshaler interface {
            UnmarshalText(text []byte) error
        }

        Subdirectories

        Name Synopsis
        ..
        ascii85 Package ascii85 implements the ascii85 data encoding as used in the btoa tool and Adobe's PostScript and PDF document formats.
        asn1 Package asn1 implements parsing of DER-encoded ASN.1 data structures, as defined in ITU-T Rec X.690.
        base32 Package base32 implements base32 encoding as specified by RFC 4648.
        base64 Package base64 implements base64 encoding as specified by RFC 4648.
        binary Package binary implements simple translation between numbers and byte sequences and encoding and decoding of varints.
        csv Package csv reads and writes comma-separated values (CSV) files.
        gob Package gob manages streams of gobs - binary values exchanged between an [Encoder] (transmitter) and a [Decoder] (receiver).
        hex Package hex implements hexadecimal encoding and decoding.
        json Package json implements encoding and decoding of JSON as defined in RFC 7159.
        pem Package pem implements the PEM data encoding, which originated in Privacy Enhanced Mail.
        xml Package xml implements a simple XML 1.0 parser that understands XML name spaces.
        ascii85 - Go Documentation Server
        ...

        Package ascii85

        import "encoding/ascii85"
        Overview
        Index

        Overview ▾

        Package ascii85 implements the ascii85 data encoding as used in the btoa tool and Adobe's PostScript and PDF document formats.

        func Decode

        func Decode(dst, src []byte, flush bool) (ndst, nsrc int, err error)

        Decode decodes src into dst, returning both the number of bytes written to dst and the number consumed from src. If src contains invalid ascii85 data, Decode will return the number of bytes successfully written and a CorruptInputError. Decode ignores space and control characters in src. Often, ascii85-encoded data is wrapped in <~ and ~> symbols. Decode expects these to have been stripped by the caller.

        If flush is true, Decode assumes that src represents the end of the input stream and processes it completely rather than wait for the completion of another 32-bit block.

        NewDecoder wraps an io.Reader interface around Decode.

        func Encode

        func Encode(dst, src []byte) int

        Encode encodes src into at most MaxEncodedLen(len(src)) bytes of dst, returning the actual number of bytes written.

        The encoding handles 4-byte chunks, using a special encoding for the last fragment, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder instead.

        Often, ascii85-encoded data is wrapped in <~ and ~> symbols. Encode does not add these.

        func MaxEncodedLen

        func MaxEncodedLen(n int) int

        MaxEncodedLen returns the maximum length of an encoding of n source bytes.

        func NewDecoder

        func NewDecoder(r io.Reader) io.Reader

        NewDecoder constructs a new ascii85 stream decoder.

        func NewEncoder

        func NewEncoder(w io.Writer) io.WriteCloser

        NewEncoder returns a new ascii85 stream encoder. Data written to the returned writer will be encoded and then written to w. Ascii85 encodings operate in 32-bit blocks; when finished writing, the caller must Close the returned encoder to flush any trailing partial block.

        type CorruptInputError

        type CorruptInputError int64

        func (CorruptInputError) Error

        func (e CorruptInputError) Error() string
        asn1 - Go Documentation Server
        ...

        Package asn1

        import "encoding/asn1"
        Overview
        Index

        Overview ▾

        Package asn1 implements parsing of DER-encoded ASN.1 data structures, as defined in ITU-T Rec X.690.

        See also “A Layman's Guide to a Subset of ASN.1, BER, and DER,” http://luca.ntop.org/Teaching/Appunti/asn1.html.

        Constants

        ASN.1 tags represent the type of the following object.

        const (
            TagBoolean         = 1
            TagInteger         = 2
            TagBitString       = 3
            TagOctetString     = 4
            TagNull            = 5
            TagOID             = 6
            TagEnum            = 10
            TagUTF8String      = 12
            TagSequence        = 16
            TagSet             = 17
            TagNumericString   = 18
            TagPrintableString = 19
            TagT61String       = 20
            TagIA5String       = 22
            TagUTCTime         = 23
            TagGeneralizedTime = 24
            TagGeneralString   = 27
            TagBMPString       = 30
        )

        ASN.1 class types represent the namespace of the tag.

        const (
            ClassUniversal       = 0
            ClassApplication     = 1
            ClassContextSpecific = 2
            ClassPrivate         = 3
        )

        Variables

        NullBytes contains bytes representing the DER-encoded ASN.1 NULL type.

        var NullBytes = []byte{TagNull, 0}

        NullRawValue is a RawValue with its Tag set to the ASN.1 NULL type tag (5).

        var NullRawValue = RawValue{Tag: TagNull}

        func Marshal

        func Marshal(val any) ([]byte, error)

        Marshal returns the ASN.1 encoding of val.

        In addition to the struct tags recognized by Unmarshal, the following can be used:

        ia5:         causes strings to be marshaled as ASN.1, IA5String values
        omitempty:   causes empty slices to be skipped
        printable:   causes strings to be marshaled as ASN.1, PrintableString values
        utf8:        causes strings to be marshaled as ASN.1, UTF8String values
        utc:         causes time.Time to be marshaled as ASN.1, UTCTime values
        generalized: causes time.Time to be marshaled as ASN.1, GeneralizedTime values
        

        func MarshalWithParams

        func MarshalWithParams(val any, params string) ([]byte, error)

        MarshalWithParams allows field parameters to be specified for the top-level element. The form of the params is the same as the field tags.

        func Unmarshal

        func Unmarshal(b []byte, val any) (rest []byte, err error)

        Unmarshal parses the DER-encoded ASN.1 data structure b and uses the reflect package to fill in an arbitrary value pointed at by val. Because Unmarshal uses the reflect package, the structs being written to must use upper case field names. If val is nil or not a pointer, Unmarshal returns an error.

        After parsing b, any bytes that were leftover and not used to fill val will be returned in rest. When parsing a SEQUENCE into a struct, any trailing elements of the SEQUENCE that do not have matching fields in val will not be included in rest, as these are considered valid elements of the SEQUENCE and not trailing data.

        • An ASN.1 INTEGER can be written to an int, int32, int64, or *big.Int. If the encoded value does not fit in the Go type, Unmarshal returns a parse error.

        • An ASN.1 BIT STRING can be written to a BitString.

        • An ASN.1 OCTET STRING can be written to a []byte.

        • An ASN.1 OBJECT IDENTIFIER can be written to an ObjectIdentifier.

        • An ASN.1 ENUMERATED can be written to an Enumerated.

        • An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time.

        • An ASN.1 PrintableString, IA5String, or NumericString can be written to a string.

        • Any of the above ASN.1 values can be written to an interface{}. The value stored in the interface has the corresponding Go type. For integers, that type is int64.

        • An ASN.1 SEQUENCE OF x or SET OF x can be written to a slice if an x can be written to the slice's element type.

        • An ASN.1 SEQUENCE or SET can be written to a struct if each of the elements in the sequence can be written to the corresponding element in the struct.

        The following tags on struct fields have special meaning to Unmarshal:

        application specifies that an APPLICATION tag is used
        private     specifies that a PRIVATE tag is used
        default:x   sets the default value for optional integer fields (only used if optional is also present)
        explicit    specifies that an additional, explicit tag wraps the implicit one
        optional    marks the field as ASN.1 OPTIONAL
        set         causes a SET, rather than a SEQUENCE type to be expected
        tag:x       specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC
        

        When decoding an ASN.1 value with an IMPLICIT tag into a string field, Unmarshal will default to a PrintableString, which doesn't support characters such as '@' and '&'. To force other encodings, use the following tags:

        ia5     causes strings to be unmarshaled as ASN.1 IA5String values
        numeric causes strings to be unmarshaled as ASN.1 NumericString values
        utf8    causes strings to be unmarshaled as ASN.1 UTF8String values
        

        If the type of the first field of a structure is RawContent then the raw ASN1 contents of the struct will be stored in it.

        If the name of a slice type ends with "SET" then it's treated as if the "set" tag was set on it. This results in interpreting the type as a SET OF x rather than a SEQUENCE OF x. This can be used with nested slices where a struct tag cannot be given.

        Other ASN.1 types are not supported; if it encounters them, Unmarshal returns a parse error.

        func UnmarshalWithParams

        func UnmarshalWithParams(b []byte, val any, params string) (rest []byte, err error)

        UnmarshalWithParams allows field parameters to be specified for the top-level element. The form of the params is the same as the field tags.

        type BitString

        BitString is the structure to use when you want an ASN.1 BIT STRING type. A bit string is padded up to the nearest byte in memory and the number of valid bits is recorded. Padding bits will be zero.

        type BitString struct {
            Bytes     []byte // bits packed into bytes.
            BitLength int    // length in bits.
        }
        

        func (BitString) At

        func (b BitString) At(i int) int

        At returns the bit at the given index. If the index is out of range it returns 0.

        func (BitString) RightAlign

        func (b BitString) RightAlign() []byte

        RightAlign returns a slice where the padding bits are at the beginning. The slice may share memory with the BitString.

        type Enumerated

        An Enumerated is represented as a plain int.

        type Enumerated int

        type Flag

        A Flag accepts any data and is set to true if present.

        type Flag bool

        type ObjectIdentifier

        An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER.

        type ObjectIdentifier []int

        func (ObjectIdentifier) Equal

        func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool

        Equal reports whether oi and other represent the same identifier.

        func (ObjectIdentifier) String

        func (oi ObjectIdentifier) String() string

        type RawContent

        RawContent is used to signal that the undecoded, DER data needs to be preserved for a struct. To use it, the first field of the struct must have this type. It's an error for any of the other fields to have this type.

        type RawContent []byte

        type RawValue

        A RawValue represents an undecoded ASN.1 object.

        type RawValue struct {
            Class, Tag int
            IsCompound bool
            Bytes      []byte
            FullBytes  []byte // includes the tag and length
        }
        

        type StructuralError

        A StructuralError suggests that the ASN.1 data is valid, but the Go type which is receiving it doesn't match.

        type StructuralError struct {
            Msg string
        }
        

        func (StructuralError) Error

        func (e StructuralError) Error() string

        type SyntaxError

        A SyntaxError suggests that the ASN.1 data is invalid.

        type SyntaxError struct {
            Msg string
        }
        

        func (SyntaxError) Error

        func (e SyntaxError) Error() string
        base32 - Go Documentation Server
        ...

        Package base32

        import "encoding/base32"
        Overview
        Index
        Examples

        Overview ▾

        Package base32 implements base32 encoding as specified by RFC 4648.

        Constants

        const (
            StdPadding rune = '=' // Standard padding character
            NoPadding  rune = -1  // No padding
        )

        Variables

        HexEncoding is the “Extended Hex Alphabet” defined in RFC 4648. It is typically used in DNS.

        var HexEncoding = NewEncoding("0123456789ABCDEFGHIJKLMNOPQRSTUV")

        StdEncoding is the standard base32 encoding, as defined in RFC 4648.

        var StdEncoding = NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")

        func NewDecoder

        func NewDecoder(enc *Encoding, r io.Reader) io.Reader

        NewDecoder constructs a new base32 stream decoder.

        func NewEncoder

        func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser

        NewEncoder returns a new base32 stream encoder. Data written to the returned writer will be encoded using enc and then written to w. Base32 encodings operate in 5-byte blocks; when finished writing, the caller must Close the returned encoder to flush any partially written blocks.

        Example

        Code:

        input := []byte("foo\x00bar")
        encoder := base32.NewEncoder(base32.StdEncoding, os.Stdout)
        encoder.Write(input)
        // Must close the encoder when finished to flush any partial blocks.
        // If you comment out the following line, the last partial block "r"
        // won't be encoded.
        encoder.Close()
        

        Output:

        MZXW6ADCMFZA====
        

        type CorruptInputError

        type CorruptInputError int64

        func (CorruptInputError) Error

        func (e CorruptInputError) Error() string

        type Encoding

        An Encoding is a radix 32 encoding/decoding scheme, defined by a 32-character alphabet. The most common is the "base32" encoding introduced for SASL GSSAPI and standardized in RFC 4648. The alternate "base32hex" encoding is used in DNSSEC.

        type Encoding struct {
            // contains filtered or unexported fields
        }
        

        func NewEncoding

        func NewEncoding(encoder string) *Encoding

        NewEncoding returns a new padded Encoding defined by the given alphabet, which must be a 32-byte string that contains unique byte values and does not contain the padding character or CR / LF ('\r', '\n'). The alphabet is treated as a sequence of byte values without any special treatment for multi-byte UTF-8. The resulting Encoding uses the default padding character ('='), which may be changed or disabled via Encoding.WithPadding.

        func (*Encoding) AppendDecode

        func (enc *Encoding) AppendDecode(dst, src []byte) ([]byte, error)

        AppendDecode appends the base32 decoded src to dst and returns the extended buffer. If the input is malformed, it returns the partially decoded src and an error.

        func (*Encoding) AppendEncode

        func (enc *Encoding) AppendEncode(dst, src []byte) []byte

        AppendEncode appends the base32 encoded src to dst and returns the extended buffer.

        func (*Encoding) Decode

        func (enc *Encoding) Decode(dst, src []byte) (n int, err error)

        Decode decodes src using the encoding enc. It writes at most Encoding.DecodedLen(len(src)) bytes to dst and returns the number of bytes written. If src contains invalid base32 data, it will return the number of bytes successfully written and CorruptInputError. Newline characters (\r and \n) are ignored.

        Example

        Code:

        str := "JBSWY3DPFQQHO33SNRSCC==="
        dst := make([]byte, base32.StdEncoding.DecodedLen(len(str)))
        n, err := base32.StdEncoding.Decode(dst, []byte(str))
        if err != nil {
            fmt.Println("decode error:", err)
            return
        }
        dst = dst[:n]
        fmt.Printf("%q\n", dst)
        

        Output:

        "Hello, world!"
        

        func (*Encoding) DecodeString

        func (enc *Encoding) DecodeString(s string) ([]byte, error)

        DecodeString returns the bytes represented by the base32 string s.

        Example

        Code:

        str := "ONXW2ZJAMRQXIYJAO5UXI2BAAAQGC3TEEDX3XPY="
        data, err := base32.StdEncoding.DecodeString(str)
        if err != nil {
            fmt.Println("error:", err)
            return
        }
        fmt.Printf("%q\n", data)
        

        Output:

        "some data with \x00 and \ufeff"
        

        func (*Encoding) DecodedLen

        func (enc *Encoding) DecodedLen(n int) int

        DecodedLen returns the maximum length in bytes of the decoded data corresponding to n bytes of base32-encoded data.

        func (*Encoding) Encode

        func (enc *Encoding) Encode(dst, src []byte)

        Encode encodes src using the encoding enc, writing Encoding.EncodedLen(len(src)) bytes to dst.

        The encoding pads the output to a multiple of 8 bytes, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder instead.

        Example

        Code:

        data := []byte("Hello, world!")
        dst := make([]byte, base32.StdEncoding.EncodedLen(len(data)))
        base32.StdEncoding.Encode(dst, data)
        fmt.Println(string(dst))
        

        Output:

        JBSWY3DPFQQHO33SNRSCC===
        

        func (*Encoding) EncodeToString

        func (enc *Encoding) EncodeToString(src []byte) string

        EncodeToString returns the base32 encoding of src.

        Example

        Code:

        data := []byte("any + old & data")
        str := base32.StdEncoding.EncodeToString(data)
        fmt.Println(str)
        

        Output:

        MFXHSIBLEBXWYZBAEYQGIYLUME======
        

        func (*Encoding) EncodedLen

        func (enc *Encoding) EncodedLen(n int) int

        EncodedLen returns the length in bytes of the base32 encoding of an input buffer of length n.

        func (Encoding) WithPadding

        func (enc Encoding) WithPadding(padding rune) *Encoding

        WithPadding creates a new encoding identical to enc except with a specified padding character, or NoPadding to disable padding. The padding character must not be '\r' or '\n', must not be contained in the encoding's alphabet, must not be negative, and must be a rune equal or below '\xff'. Padding characters above '\x7f' are encoded as their exact byte value rather than using the UTF-8 representation of the codepoint.

        base64 - Go Documentation Server
        ...

        Package base64

        import "encoding/base64"
        Overview
        Index
        Examples

        Overview ▾

        Package base64 implements base64 encoding as specified by RFC 4648.

        Example

        Code:

        msg := "Hello, 世界"
        encoded := base64.StdEncoding.EncodeToString([]byte(msg))
        fmt.Println(encoded)
        decoded, err := base64.StdEncoding.DecodeString(encoded)
        if err != nil {
            fmt.Println("decode error:", err)
            return
        }
        fmt.Println(string(decoded))
        

        Output:

        SGVsbG8sIOS4lueVjA==
        Hello, 世界
        

        Constants

        const (
            StdPadding rune = '=' // Standard padding character
            NoPadding  rune = -1  // No padding
        )

        Variables

        RawStdEncoding is the standard raw, unpadded base64 encoding, as defined in RFC 4648 section 3.2. This is the same as StdEncoding but omits padding characters.

        var RawStdEncoding = StdEncoding.WithPadding(NoPadding)

        RawURLEncoding is the unpadded alternate base64 encoding defined in RFC 4648. It is typically used in URLs and file names. This is the same as URLEncoding but omits padding characters.

        var RawURLEncoding = URLEncoding.WithPadding(NoPadding)

        StdEncoding is the standard base64 encoding, as defined in RFC 4648.

        var StdEncoding = NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")

        URLEncoding is the alternate base64 encoding defined in RFC 4648. It is typically used in URLs and file names.

        var URLEncoding = NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")

        func NewDecoder

        func NewDecoder(enc *Encoding, r io.Reader) io.Reader

        NewDecoder constructs a new base64 stream decoder.

        func NewEncoder

        func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser

        NewEncoder returns a new base64 stream encoder. Data written to the returned writer will be encoded using enc and then written to w. Base64 encodings operate in 4-byte blocks; when finished writing, the caller must Close the returned encoder to flush any partially written blocks.

        Example

        Code:

        input := []byte("foo\x00bar")
        encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
        encoder.Write(input)
        // Must close the encoder when finished to flush any partial blocks.
        // If you comment out the following line, the last partial block "r"
        // won't be encoded.
        encoder.Close()
        

        Output:

        Zm9vAGJhcg==
        

        type CorruptInputError

        type CorruptInputError int64

        func (CorruptInputError) Error

        func (e CorruptInputError) Error() string

        type Encoding

        An Encoding is a radix 64 encoding/decoding scheme, defined by a 64-character alphabet. The most common encoding is the "base64" encoding defined in RFC 4648 and used in MIME (RFC 2045) and PEM (RFC 1421). RFC 4648 also defines an alternate encoding, which is the standard encoding with - and _ substituted for + and /.

        type Encoding struct {
            // contains filtered or unexported fields
        }
        

        func NewEncoding

        func NewEncoding(encoder string) *Encoding

        NewEncoding returns a new padded Encoding defined by the given alphabet, which must be a 64-byte string that contains unique byte values and does not contain the padding character or CR / LF ('\r', '\n'). The alphabet is treated as a sequence of byte values without any special treatment for multi-byte UTF-8. The resulting Encoding uses the default padding character ('='), which may be changed or disabled via Encoding.WithPadding.

        func (*Encoding) AppendDecode

        func (enc *Encoding) AppendDecode(dst, src []byte) ([]byte, error)

        AppendDecode appends the base64 decoded src to dst and returns the extended buffer. If the input is malformed, it returns the partially decoded src and an error.

        func (*Encoding) AppendEncode

        func (enc *Encoding) AppendEncode(dst, src []byte) []byte

        AppendEncode appends the base64 encoded src to dst and returns the extended buffer.

        func (*Encoding) Decode

        func (enc *Encoding) Decode(dst, src []byte) (n int, err error)

        Decode decodes src using the encoding enc. It writes at most Encoding.DecodedLen(len(src)) bytes to dst and returns the number of bytes written. If src contains invalid base64 data, it will return the number of bytes successfully written and CorruptInputError. New line characters (\r and \n) are ignored.

        Example

        Code:

        str := "SGVsbG8sIHdvcmxkIQ=="
        dst := make([]byte, base64.StdEncoding.DecodedLen(len(str)))
        n, err := base64.StdEncoding.Decode(dst, []byte(str))
        if err != nil {
            fmt.Println("decode error:", err)
            return
        }
        dst = dst[:n]
        fmt.Printf("%q\n", dst)
        

        Output:

        "Hello, world!"
        

        func (*Encoding) DecodeString

        func (enc *Encoding) DecodeString(s string) ([]byte, error)

        DecodeString returns the bytes represented by the base64 string s.

        Example

        Code:

        str := "c29tZSBkYXRhIHdpdGggACBhbmQg77u/"
        data, err := base64.StdEncoding.DecodeString(str)
        if err != nil {
            fmt.Println("error:", err)
            return
        }
        fmt.Printf("%q\n", data)
        

        Output:

        "some data with \x00 and \ufeff"
        

        func (*Encoding) DecodedLen

        func (enc *Encoding) DecodedLen(n int) int

        DecodedLen returns the maximum length in bytes of the decoded data corresponding to n bytes of base64-encoded data.

        func (*Encoding) Encode

        func (enc *Encoding) Encode(dst, src []byte)

        Encode encodes src using the encoding enc, writing Encoding.EncodedLen(len(src)) bytes to dst.

        The encoding pads the output to a multiple of 4 bytes, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder instead.

        Example

        Code:

        data := []byte("Hello, world!")
        dst := make([]byte, base64.StdEncoding.EncodedLen(len(data)))
        base64.StdEncoding.Encode(dst, data)
        fmt.Println(string(dst))
        

        Output:

        SGVsbG8sIHdvcmxkIQ==
        

        func (*Encoding) EncodeToString

        func (enc *Encoding) EncodeToString(src []byte) string

        EncodeToString returns the base64 encoding of src.

        Example

        Code:

        data := []byte("any + old & data")
        str := base64.StdEncoding.EncodeToString(data)
        fmt.Println(str)
        

        Output:

        YW55ICsgb2xkICYgZGF0YQ==
        

        func (*Encoding) EncodedLen

        func (enc *Encoding) EncodedLen(n int) int

        EncodedLen returns the length in bytes of the base64 encoding of an input buffer of length n.

        func (Encoding) Strict

        func (enc Encoding) Strict() *Encoding

        Strict creates a new encoding identical to enc except with strict decoding enabled. In this mode, the decoder requires that trailing padding bits are zero, as described in RFC 4648 section 3.5.

        Note that the input is still malleable, as new line characters (CR and LF) are still ignored.

        func (Encoding) WithPadding

        func (enc Encoding) WithPadding(padding rune) *Encoding

        WithPadding creates a new encoding identical to enc except with a specified padding character, or NoPadding to disable padding. The padding character must not be '\r' or '\n', must not be contained in the encoding's alphabet, must not be negative, and must be a rune equal or below '\xff'. Padding characters above '\x7f' are encoded as their exact byte value rather than using the UTF-8 representation of the codepoint.

        binary - Go Documentation Server
        ...

        Package binary

        import "encoding/binary"
        Overview
        Index
        Examples

        Overview ▾

        Package binary implements simple translation between numbers and byte sequences and encoding and decoding of varints.

        Numbers are translated by reading and writing fixed-size values. A fixed-size value is either a fixed-size arithmetic type (bool, int8, uint8, int16, float32, complex64, ...) or an array or struct containing only fixed-size values.

        The varint functions encode and decode single integer values using a variable-length encoding; smaller values require fewer bytes. For a specification, see https://developers.google.com/protocol-buffers/docs/encoding.

        This package favors simplicity over efficiency. Clients that require high-performance serialization, especially for large data structures, should look at more advanced solutions such as the encoding/gob package or google.golang.org/protobuf for protocol buffers.

        Constants

        MaxVarintLenN is the maximum length of a varint-encoded N-bit integer.

        const (
            MaxVarintLen16 = 3
            MaxVarintLen32 = 5
            MaxVarintLen64 = 10
        )

        Variables

        BigEndian is the big-endian implementation of ByteOrder and AppendByteOrder.

        var BigEndian bigEndian

        LittleEndian is the little-endian implementation of ByteOrder and AppendByteOrder.

        var LittleEndian littleEndian

        NativeEndian is the native-endian implementation of ByteOrder and AppendByteOrder.

        var NativeEndian nativeEndian

        func AppendUvarint

        func AppendUvarint(buf []byte, x uint64) []byte

        AppendUvarint appends the varint-encoded form of x, as generated by PutUvarint, to buf and returns the extended buffer.

        func AppendVarint

        func AppendVarint(buf []byte, x int64) []byte

        AppendVarint appends the varint-encoded form of x, as generated by PutVarint, to buf and returns the extended buffer.

        func PutUvarint

        func PutUvarint(buf []byte, x uint64) int

        PutUvarint encodes a uint64 into buf and returns the number of bytes written. If the buffer is too small, PutUvarint will panic.

        Example

        Code:

        buf := make([]byte, binary.MaxVarintLen64)
        
        for _, x := range []uint64{1, 2, 127, 128, 255, 256} {
            n := binary.PutUvarint(buf, x)
            fmt.Printf("%x\n", buf[:n])
        }
        

        Output:

        01
        02
        7f
        8001
        ff01
        8002
        

        func PutVarint

        func PutVarint(buf []byte, x int64) int

        PutVarint encodes an int64 into buf and returns the number of bytes written. If the buffer is too small, PutVarint will panic.

        Example

        Code:

        buf := make([]byte, binary.MaxVarintLen64)
        
        for _, x := range []int64{-65, -64, -2, -1, 0, 1, 2, 63, 64} {
            n := binary.PutVarint(buf, x)
            fmt.Printf("%x\n", buf[:n])
        }
        

        Output:

        8101
        7f
        03
        01
        00
        02
        04
        7e
        8001
        

        func Read

        func Read(r io.Reader, order ByteOrder, data any) error

        Read reads structured binary data from r into data. Data must be a pointer to a fixed-size value or a slice of fixed-size values. Bytes read from r are decoded using the specified byte order and written to successive fields of the data. When decoding boolean values, a zero byte is decoded as false, and any other non-zero byte is decoded as true. When reading into structs, the field data for fields with blank (_) field names is skipped; i.e., blank field names may be used for padding. When reading into a struct, all non-blank fields must be exported or Read may panic.

        The error is io.EOF only if no bytes were read. If an io.EOF happens after reading some but not all the bytes, Read returns io.ErrUnexpectedEOF.

        Example

        Code:

        var pi float64
        b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40}
        buf := bytes.NewReader(b)
        err := binary.Read(buf, binary.LittleEndian, &pi)
        if err != nil {
            fmt.Println("binary.Read failed:", err)
        }
        fmt.Print(pi)
        

        Output:

        3.141592653589793
        

        Example (Multi)

        Code:

        b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40, 0xff, 0x01, 0x02, 0x03, 0xbe, 0xef}
        r := bytes.NewReader(b)
        
        var data struct {
            PI   float64
            Uate uint8
            Mine [3]byte
            Too  uint16
        }
        
        if err := binary.Read(r, binary.LittleEndian, &data); err != nil {
            fmt.Println("binary.Read failed:", err)
        }
        
        fmt.Println(data.PI)
        fmt.Println(data.Uate)
        fmt.Printf("% x\n", data.Mine)
        fmt.Println(data.Too)
        

        Output:

        3.141592653589793
        255
        01 02 03
        61374
        

        func ReadUvarint

        func ReadUvarint(r io.ByteReader) (uint64, error)

        ReadUvarint reads an encoded unsigned integer from r and returns it as a uint64. The error is io.EOF only if no bytes were read. If an io.EOF happens after reading some but not all the bytes, ReadUvarint returns io.ErrUnexpectedEOF.

        func ReadVarint

        func ReadVarint(r io.ByteReader) (int64, error)

        ReadVarint reads an encoded signed integer from r and returns it as an int64. The error is io.EOF only if no bytes were read. If an io.EOF happens after reading some but not all the bytes, ReadVarint returns io.ErrUnexpectedEOF.

        func Size

        func Size(v any) int

        Size returns how many bytes Write would generate to encode the value v, which must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. If v is neither of these, Size returns -1.

        func Uvarint

        func Uvarint(buf []byte) (uint64, int)

        Uvarint decodes a uint64 from buf and returns that value and the number of bytes read (> 0). If an error occurred, the value is 0 and the number of bytes n is <= 0 meaning:

        n == 0: buf too small
        n  < 0: value larger than 64 bits (overflow)
                and -n is the number of bytes read
        

        Example

        Code:

        inputs := [][]byte{
            {0x01},
            {0x02},
            {0x7f},
            {0x80, 0x01},
            {0xff, 0x01},
            {0x80, 0x02},
        }
        for _, b := range inputs {
            x, n := binary.Uvarint(b)
            if n != len(b) {
                fmt.Println("Uvarint did not consume all of in")
            }
            fmt.Println(x)
        }
        

        Output:

        1
        2
        127
        128
        255
        256
        

        func Varint

        func Varint(buf []byte) (int64, int)

        Varint decodes an int64 from buf and returns that value and the number of bytes read (> 0). If an error occurred, the value is 0 and the number of bytes n is <= 0 with the following meaning:

        n == 0: buf too small
        n  < 0: value larger than 64 bits (overflow)
                and -n is the number of bytes read
        

        Example

        Code:

        inputs := [][]byte{
            {0x81, 0x01},
            {0x7f},
            {0x03},
            {0x01},
            {0x00},
            {0x02},
            {0x04},
            {0x7e},
            {0x80, 0x01},
        }
        for _, b := range inputs {
            x, n := binary.Varint(b)
            if n != len(b) {
                fmt.Println("Varint did not consume all of in")
            }
            fmt.Println(x)
        }
        

        Output:

        -65
        -64
        -2
        -1
        0
        1
        2
        63
        64
        

        func Write

        func Write(w io.Writer, order ByteOrder, data any) error

        Write writes the binary representation of data into w. Data must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. Boolean values encode as one byte: 1 for true, and 0 for false. Bytes written to w are encoded using the specified byte order and read from successive fields of the data. When writing structs, zero values are written for fields with blank (_) field names.

        Example

        Code:

        buf := new(bytes.Buffer)
        var pi float64 = math.Pi
        err := binary.Write(buf, binary.LittleEndian, pi)
        if err != nil {
            fmt.Println("binary.Write failed:", err)
        }
        fmt.Printf("% x", buf.Bytes())
        

        Output:

        18 2d 44 54 fb 21 09 40
        

        Example (Multi)

        Code:

        buf := new(bytes.Buffer)
        var data = []any{
            uint16(61374),
            int8(-54),
            uint8(254),
        }
        for _, v := range data {
            err := binary.Write(buf, binary.LittleEndian, v)
            if err != nil {
                fmt.Println("binary.Write failed:", err)
            }
        }
        fmt.Printf("%x", buf.Bytes())
        

        Output:

        beefcafe
        

        type AppendByteOrder

        AppendByteOrder specifies how to append 16-, 32-, or 64-bit unsigned integers into a byte slice.

        It is implemented by LittleEndian, BigEndian, and NativeEndian.

        type AppendByteOrder interface {
            AppendUint16([]byte, uint16) []byte
            AppendUint32([]byte, uint32) []byte
            AppendUint64([]byte, uint64) []byte
            String() string
        }

        type ByteOrder

        A ByteOrder specifies how to convert byte slices into 16-, 32-, or 64-bit unsigned integers.

        It is implemented by LittleEndian, BigEndian, and NativeEndian.

        type ByteOrder interface {
            Uint16([]byte) uint16
            Uint32([]byte) uint32
            Uint64([]byte) uint64
            PutUint16([]byte, uint16)
            PutUint32([]byte, uint32)
            PutUint64([]byte, uint64)
            String() string
        }

        Example (Get)

        Code:

        b := []byte{0xe8, 0x03, 0xd0, 0x07}
        x1 := binary.LittleEndian.Uint16(b[0:])
        x2 := binary.LittleEndian.Uint16(b[2:])
        fmt.Printf("%#04x %#04x\n", x1, x2)
        

        Output:

        0x03e8 0x07d0
        

        Example (Put)

        Code:

        b := make([]byte, 4)
        binary.LittleEndian.PutUint16(b[0:], 0x03e8)
        binary.LittleEndian.PutUint16(b[2:], 0x07d0)
        fmt.Printf("% x\n", b)
        

        Output:

        e8 03 d0 07
        
        csv - Go Documentation Server
        ...

        Package csv

        import "encoding/csv"
        Overview
        Index
        Examples

        Overview ▾

        Package csv reads and writes comma-separated values (CSV) files. There are many kinds of CSV files; this package supports the format described in RFC 4180.

        A csv file contains zero or more records of one or more fields per record. Each record is separated by the newline character. The final record may optionally be followed by a newline character.

        field1,field2,field3
        

        White space is considered part of a field.

        Carriage returns before newline characters are silently removed.

        Blank lines are ignored. A line with only whitespace characters (excluding the ending newline character) is not considered a blank line.

        Fields which start and stop with the quote character " are called quoted-fields. The beginning and ending quote are not part of the field.

        The source:

        normal string,"quoted-field"
        

        results in the fields

        {`normal string`, `quoted-field`}
        

        Within a quoted-field a quote character followed by a second quote character is considered a single quote.

        "the ""word"" is true","a ""quoted-field"""
        

        results in

        {`the "word" is true`, `a "quoted-field"`}
        

        Newlines and commas may be included in a quoted-field

        "Multi-line
        field","comma is ,"
        

        results in

        {`Multi-line
        field`, `comma is ,`}
        

        Variables

        These are the errors that can be returned in [ParseError.Err].

        var (
            ErrBareQuote  = errors.New("bare \" in non-quoted-field")
            ErrQuote      = errors.New("extraneous or missing \" in quoted-field")
            ErrFieldCount = errors.New("wrong number of fields")
        
            // Deprecated: ErrTrailingComma is no longer used.
            ErrTrailingComma = errors.New("extra delimiter at end of line")
        )

        type ParseError

        A ParseError is returned for parsing errors. Line and column numbers are 1-indexed.

        type ParseError struct {
            StartLine int   // Line where the record starts
            Line      int   // Line where the error occurred
            Column    int   // Column (1-based byte index) where the error occurred
            Err       error // The actual error
        }
        

        func (*ParseError) Error

        func (e *ParseError) Error() string

        func (*ParseError) Unwrap

        func (e *ParseError) Unwrap() error

        type Reader

        A Reader reads records from a CSV-encoded file.

        As returned by NewReader, a Reader expects input conforming to RFC 4180. The exported fields can be changed to customize the details before the first call to Reader.Read or Reader.ReadAll.

        The Reader converts all \r\n sequences in its input to plain \n, including in multiline field values, so that the returned data does not depend on which line-ending convention an input file uses.

        type Reader struct {
            // Comma is the field delimiter.
            // It is set to comma (',') by NewReader.
            // Comma must be a valid rune and must not be \r, \n,
            // or the Unicode replacement character (0xFFFD).
            Comma rune
        
            // Comment, if not 0, is the comment character. Lines beginning with the
            // Comment character without preceding whitespace are ignored.
            // With leading whitespace the Comment character becomes part of the
            // field, even if TrimLeadingSpace is true.
            // Comment must be a valid rune and must not be \r, \n,
            // or the Unicode replacement character (0xFFFD).
            // It must also not be equal to Comma.
            Comment rune
        
            // FieldsPerRecord is the number of expected fields per record.
            // If FieldsPerRecord is positive, Read requires each record to
            // have the given number of fields. If FieldsPerRecord is 0, Read sets it to
            // the number of fields in the first record, so that future records must
            // have the same field count. If FieldsPerRecord is negative, no check is
            // made and records may have a variable number of fields.
            FieldsPerRecord int
        
            // If LazyQuotes is true, a quote may appear in an unquoted field and a
            // non-doubled quote may appear in a quoted field.
            LazyQuotes bool
        
            // If TrimLeadingSpace is true, leading white space in a field is ignored.
            // This is done even if the field delimiter, Comma, is white space.
            TrimLeadingSpace bool
        
            // ReuseRecord controls whether calls to Read may return a slice sharing
            // the backing array of the previous call's returned slice for performance.
            // By default, each call to Read returns newly allocated memory owned by the caller.
            ReuseRecord bool
        
            // Deprecated: TrailingComma is no longer used.
            TrailingComma bool
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        in := `first_name,last_name,username
        "Rob","Pike",rob
        Ken,Thompson,ken
        "Robert","Griesemer","gri"
        `
        r := csv.NewReader(strings.NewReader(in))
        
        for {
            record, err := r.Read()
            if err == io.EOF {
                break
            }
            if err != nil {
                log.Fatal(err)
            }
        
            fmt.Println(record)
        }
        

        Output:

        [first_name last_name username]
        [Rob Pike rob]
        [Ken Thompson ken]
        [Robert Griesemer gri]
        

        Example (Options)

        This example shows how csv.Reader can be configured to handle other types of CSV files.

        Code:

        in := `first_name;last_name;username
        "Rob";"Pike";rob
        # lines beginning with a # character are ignored
        Ken;Thompson;ken
        "Robert";"Griesemer";"gri"
        `
        r := csv.NewReader(strings.NewReader(in))
        r.Comma = ';'
        r.Comment = '#'
        
        records, err := r.ReadAll()
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Print(records)
        

        Output:

        [[first_name last_name username] [Rob Pike rob] [Ken Thompson ken] [Robert Griesemer gri]]
        

        func NewReader

        func NewReader(r io.Reader) *Reader

        NewReader returns a new Reader that reads from r.

        func (*Reader) FieldPos

        func (r *Reader) FieldPos(field int) (line, column int)

        FieldPos returns the line and column corresponding to the start of the field with the given index in the slice most recently returned by Reader.Read. Numbering of lines and columns starts at 1; columns are counted in bytes, not runes.

        If this is called with an out-of-bounds index, it panics.

        func (*Reader) InputOffset

        func (r *Reader) InputOffset() int64

        InputOffset returns the input stream byte offset of the current reader position. The offset gives the location of the end of the most recently read row and the beginning of the next row.

        func (*Reader) Read

        func (r *Reader) Read() (record []string, err error)

        Read reads one record (a slice of fields) from r. If the record has an unexpected number of fields, Read returns the record along with the error ErrFieldCount. If the record contains a field that cannot be parsed, Read returns a partial record along with the parse error. The partial record contains all fields read before the error. If there is no data left to be read, Read returns nil, io.EOF. If [Reader.ReuseRecord] is true, the returned slice may be shared between multiple calls to Read.

        func (*Reader) ReadAll

        func (r *Reader) ReadAll() (records [][]string, err error)

        ReadAll reads all the remaining records from r. Each record is a slice of fields. A successful call returns err == nil, not err == io.EOF. Because ReadAll is defined to read until EOF, it does not treat end of file as an error to be reported.

        Example

        Code:

        in := `first_name,last_name,username
        "Rob","Pike",rob
        Ken,Thompson,ken
        "Robert","Griesemer","gri"
        `
        r := csv.NewReader(strings.NewReader(in))
        
        records, err := r.ReadAll()
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Print(records)
        

        Output:

        [[first_name last_name username] [Rob Pike rob] [Ken Thompson ken] [Robert Griesemer gri]]
        

        type Writer

        A Writer writes records using CSV encoding.

        As returned by NewWriter, a Writer writes records terminated by a newline and uses ',' as the field delimiter. The exported fields can be changed to customize the details before the first call to Writer.Write or Writer.WriteAll.

        [Writer.Comma] is the field delimiter.

        If [Writer.UseCRLF] is true, the Writer ends each output line with \r\n instead of \n.

        The writes of individual records are buffered. After all data has been written, the client should call the Writer.Flush method to guarantee all data has been forwarded to the underlying io.Writer. Any errors that occurred should be checked by calling the Writer.Error method.

        type Writer struct {
            Comma   rune // Field delimiter (set to ',' by NewWriter)
            UseCRLF bool // True to use \r\n as the line terminator
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        records := [][]string{
            {"first_name", "last_name", "username"},
            {"Rob", "Pike", "rob"},
            {"Ken", "Thompson", "ken"},
            {"Robert", "Griesemer", "gri"},
        }
        
        w := csv.NewWriter(os.Stdout)
        
        for _, record := range records {
            if err := w.Write(record); err != nil {
                log.Fatalln("error writing record to csv:", err)
            }
        }
        
        // Write any buffered data to the underlying writer (standard output).
        w.Flush()
        
        if err := w.Error(); err != nil {
            log.Fatal(err)
        }
        

        Output:

        first_name,last_name,username
        Rob,Pike,rob
        Ken,Thompson,ken
        Robert,Griesemer,gri
        

        func NewWriter

        func NewWriter(w io.Writer) *Writer

        NewWriter returns a new Writer that writes to w.

        func (*Writer) Error

        func (w *Writer) Error() error

        Error reports any error that has occurred during a previous Writer.Write or Writer.Flush.

        func (*Writer) Flush

        func (w *Writer) Flush()

        Flush writes any buffered data to the underlying io.Writer. To check if an error occurred during Flush, call Writer.Error.

        func (*Writer) Write

        func (w *Writer) Write(record []string) error

        Write writes a single CSV record to w along with any necessary quoting. A record is a slice of strings with each string being one field. Writes are buffered, so Writer.Flush must eventually be called to ensure that the record is written to the underlying io.Writer.

        func (*Writer) WriteAll

        func (w *Writer) WriteAll(records [][]string) error

        WriteAll writes multiple CSV records to w using Writer.Write and then calls Writer.Flush, returning any error from the Flush.

        Example

        Code:

        records := [][]string{
            {"first_name", "last_name", "username"},
            {"Rob", "Pike", "rob"},
            {"Ken", "Thompson", "ken"},
            {"Robert", "Griesemer", "gri"},
        }
        
        w := csv.NewWriter(os.Stdout)
        w.WriteAll(records) // calls Flush internally
        
        if err := w.Error(); err != nil {
            log.Fatalln("error writing csv:", err)
        }
        

        Output:

        first_name,last_name,username
        Rob,Pike,rob
        Ken,Thompson,ken
        Robert,Griesemer,gri
        
        gob - Go Documentation Server
        ...

        Package gob

        import "encoding/gob"
        Overview
        Index
        Examples

        Overview ▾

        Package gob manages streams of gobs - binary values exchanged between an Encoder (transmitter) and a Decoder (receiver). A typical use is transporting arguments and results of remote procedure calls (RPCs) such as those provided by net/rpc.

        The implementation compiles a custom codec for each data type in the stream and is most efficient when a single Encoder is used to transmit a stream of values, amortizing the cost of compilation.

        Basics

        A stream of gobs is self-describing. Each data item in the stream is preceded by a specification of its type, expressed in terms of a small set of predefined types. Pointers are not transmitted, but the things they point to are transmitted; that is, the values are flattened. Nil pointers are not permitted, as they have no value. Recursive types work fine, but recursive values (data with cycles) are problematic. This may change.

        To use gobs, create an Encoder and present it with a series of data items as values or addresses that can be dereferenced to values. The Encoder makes sure all type information is sent before it is needed. At the receive side, a Decoder retrieves values from the encoded stream and unpacks them into local variables.

        Types and Values

        The source and destination values/types need not correspond exactly. For structs, fields (identified by name) that are in the source but absent from the receiving variable will be ignored. Fields that are in the receiving variable but missing from the transmitted type or value will be ignored in the destination. If a field with the same name is present in both, their types must be compatible. Both the receiver and transmitter will do all necessary indirection and dereferencing to convert between gobs and actual Go values. For instance, a gob type that is schematically,

        struct { A, B int }
        

        can be sent from or received into any of these Go types:

        struct { A, B int }	// the same
        *struct { A, B int }	// extra indirection of the struct
        struct { *A, **B int }	// extra indirection of the fields
        struct { A, B int64 }	// different concrete value type; see below
        

        It may also be received into any of these:

        struct { A, B int }	// the same
        struct { B, A int }	// ordering doesn't matter; matching is by name
        struct { A, B, C int }	// extra field (C) ignored
        struct { B int }	// missing field (A) ignored; data will be dropped
        struct { B, C int }	// missing field (A) ignored; extra field (C) ignored.
        

        Attempting to receive into these types will draw a decode error:

        struct { A int; B uint }	// change of signedness for B
        struct { A int; B float }	// change of type for B
        struct { }			// no field names in common
        struct { C, D int }		// no field names in common
        

        Integers are transmitted two ways: arbitrary precision signed integers or arbitrary precision unsigned integers. There is no int8, int16 etc. discrimination in the gob format; there are only signed and unsigned integers. As described below, the transmitter sends the value in a variable-length encoding; the receiver accepts the value and stores it in the destination variable. Floating-point numbers are always sent using IEEE-754 64-bit precision (see below).

        Signed integers may be received into any signed integer variable: int, int16, etc.; unsigned integers may be received into any unsigned integer variable; and floating point values may be received into any floating point variable. However, the destination variable must be able to represent the value or the decode operation will fail.

        Structs, arrays and slices are also supported. Structs encode and decode only exported fields. Strings and arrays of bytes are supported with a special, efficient representation (see below). When a slice is decoded, if the existing slice has capacity the slice will be extended in place; if not, a new array is allocated. Regardless, the length of the resulting slice reports the number of elements decoded.

        In general, if allocation is required, the decoder will allocate memory. If not, it will update the destination variables with values read from the stream. It does not initialize them first, so if the destination is a compound value such as a map, struct, or slice, the decoded values will be merged elementwise into the existing variables.

        Functions and channels will not be sent in a gob. Attempting to encode such a value at the top level will fail. A struct field of chan or func type is treated exactly like an unexported field and is ignored.

        Gob can encode a value of any type implementing the GobEncoder or encoding.BinaryMarshaler interfaces by calling the corresponding method, in that order of preference.

        Gob can decode a value of any type implementing the GobDecoder or encoding.BinaryUnmarshaler interfaces by calling the corresponding method, again in that order of preference.

        Encoding Details

        This section documents the encoding, details that are not important for most users. Details are presented bottom-up.

        An unsigned integer is sent one of two ways. If it is less than 128, it is sent as a byte with that value. Otherwise it is sent as a minimal-length big-endian (high byte first) byte stream holding the value, preceded by one byte holding the byte count, negated. Thus 0 is transmitted as (00), 7 is transmitted as (07) and 256 is transmitted as (FE 01 00).

        A boolean is encoded within an unsigned integer: 0 for false, 1 for true.

        A signed integer, i, is encoded within an unsigned integer, u. Within u, bits 1 upward contain the value; bit 0 says whether they should be complemented upon receipt. The encode algorithm looks like this:

        var u uint
        if i < 0 {
        	u = (^uint(i) << 1) | 1 // complement i, bit 0 is 1
        } else {
        	u = (uint(i) << 1) // do not complement i, bit 0 is 0
        }
        encodeUnsigned(u)
        

        The low bit is therefore analogous to a sign bit, but making it the complement bit instead guarantees that the largest negative integer is not a special case. For example, -129=^128=(^256>>1) encodes as (FE 01 01).

        Floating-point numbers are always sent as a representation of a float64 value. That value is converted to a uint64 using math.Float64bits. The uint64 is then byte-reversed and sent as a regular unsigned integer. The byte-reversal means the exponent and high-precision part of the mantissa go first. Since the low bits are often zero, this can save encoding bytes. For instance, 17.0 is encoded in only three bytes (FE 31 40).

        Strings and slices of bytes are sent as an unsigned count followed by that many uninterpreted bytes of the value.

        All other slices and arrays are sent as an unsigned count followed by that many elements using the standard gob encoding for their type, recursively.

        Maps are sent as an unsigned count followed by that many key, element pairs. Empty but non-nil maps are sent, so if the receiver has not allocated one already, one will always be allocated on receipt unless the transmitted map is nil and not at the top level.

        In slices and arrays, as well as maps, all elements, even zero-valued elements, are transmitted, even if all the elements are zero.

        Structs are sent as a sequence of (field number, field value) pairs. The field value is sent using the standard gob encoding for its type, recursively. If a field has the zero value for its type (except for arrays; see above), it is omitted from the transmission. The field number is defined by the type of the encoded struct: the first field of the encoded type is field 0, the second is field 1, etc. When encoding a value, the field numbers are delta encoded for efficiency and the fields are always sent in order of increasing field number; the deltas are therefore unsigned. The initialization for the delta encoding sets the field number to -1, so an unsigned integer field 0 with value 7 is transmitted as unsigned delta = 1, unsigned value = 7 or (01 07). Finally, after all the fields have been sent a terminating mark denotes the end of the struct. That mark is a delta=0 value, which has representation (00).

        Interface types are not checked for compatibility; all interface types are treated, for transmission, as members of a single "interface" type, analogous to int or []byte - in effect they're all treated as interface{}. Interface values are transmitted as a string identifying the concrete type being sent (a name that must be pre-defined by calling Register), followed by a byte count of the length of the following data (so the value can be skipped if it cannot be stored), followed by the usual encoding of concrete (dynamic) value stored in the interface value. (A nil interface value is identified by the empty string and transmits no value.) Upon receipt, the decoder verifies that the unpacked concrete item satisfies the interface of the receiving variable.

        If a value is passed to Encoder.Encode and the type is not a struct (or pointer to struct, etc.), for simplicity of processing it is represented as a struct of one field. The only visible effect of this is to encode a zero byte after the value, just as after the last field of an encoded struct, so that the decode algorithm knows when the top-level value is complete.

        The representation of types is described below. When a type is defined on a given connection between an Encoder and Decoder, it is assigned a signed integer type id. When Encoder.Encode(v) is called, it makes sure there is an id assigned for the type of v and all its elements and then it sends the pair (typeid, encoded-v) where typeid is the type id of the encoded type of v and encoded-v is the gob encoding of the value v.

        To define a type, the encoder chooses an unused, positive type id and sends the pair (-type id, encoded-type) where encoded-type is the gob encoding of a wireType description, constructed from these types:

        type wireType struct {
        	ArrayT           *ArrayType
        	SliceT           *SliceType
        	StructT          *StructType
        	MapT             *MapType
        	GobEncoderT      *gobEncoderType
        	BinaryMarshalerT *gobEncoderType
        	TextMarshalerT   *gobEncoderType
        
        }
        type arrayType struct {
        	CommonType
        	Elem typeId
        	Len  int
        }
        type CommonType struct {
        	Name string // the name of the struct type
        	Id  int    // the id of the type, repeated so it's inside the type
        }
        type sliceType struct {
        	CommonType
        	Elem typeId
        }
        type structType struct {
        	CommonType
        	Field []*fieldType // the fields of the struct.
        }
        type fieldType struct {
        	Name string // the name of the field.
        	Id   int    // the type id of the field, which must be already defined
        }
        type mapType struct {
        	CommonType
        	Key  typeId
        	Elem typeId
        }
        type gobEncoderType struct {
        	CommonType
        }
        

        If there are nested type ids, the types for all inner type ids must be defined before the top-level type id is used to describe an encoded-v.

        For simplicity in setup, the connection is defined to understand these types a priori, as well as the basic gob types int, uint, etc. Their ids are:

        bool        1
        int         2
        uint        3
        float       4
        []byte      5
        string      6
        complex     7
        interface   8
        // gap for reserved ids.
        WireType    16
        ArrayType   17
        CommonType  18
        SliceType   19
        StructType  20
        FieldType   21
        // 22 is slice of fieldType.
        MapType     23
        

        Finally, each message created by a call to Encode is preceded by an encoded unsigned integer count of the number of bytes remaining in the message. After the initial type name, interface values are wrapped the same way; in effect, the interface value acts like a recursive invocation of Encode.

        In summary, a gob stream looks like

        (byteCount (-type id, encoding of a wireType)* (type id, encoding of a value))*
        

        where * signifies zero or more repetitions and the type id of a value must be predefined or be defined before the value in the stream.

        Compatibility: Any future changes to the package will endeavor to maintain compatibility with streams encoded using previous versions. That is, any released version of this package should be able to decode data written with any previously released version, subject to issues such as security fixes. See the Go compatibility document for background: https://golang.org/doc/go1compat

        See "Gobs of data" for a design discussion of the gob wire format: https://blog.golang.org/gobs-of-data

        Security

        This package is not designed to be hardened against adversarial inputs, and is outside the scope of https://go.dev/security/policy. In particular, the Decoder does only basic sanity checking on decoded input sizes, and its limits are not configurable. Care should be taken when decoding gob data from untrusted sources, which may consume significant resources.

        Example (Basic)

        This example shows the basic usage of the package: Create an encoder, transmit some values, receive them with a decoder.

        Code:

        package gob_test
        
        import (
            "bytes"
            "encoding/gob"
            "fmt"
            "log"
        )
        
        type P struct {
            X, Y, Z int
            Name    string
        }
        
        type Q struct {
            X, Y *int32
            Name string
        }
        
        // This example shows the basic usage of the package: Create an encoder,
        // transmit some values, receive them with a decoder.
        func Example_basic() {
            // Initialize the encoder and decoder. Normally enc and dec would be
            // bound to network connections and the encoder and decoder would
            // run in different processes.
            var network bytes.Buffer        // Stand-in for a network connection
            enc := gob.NewEncoder(&network) // Will write to network.
            dec := gob.NewDecoder(&network) // Will read from network.
        
            // Encode (send) some values.
            err := enc.Encode(P{3, 4, 5, "Pythagoras"})
            if err != nil {
                log.Fatal("encode error:", err)
            }
            err = enc.Encode(P{1782, 1841, 1922, "Treehouse"})
            if err != nil {
                log.Fatal("encode error:", err)
            }
        
            // Decode (receive) and print the values.
            var q Q
            err = dec.Decode(&q)
            if err != nil {
                log.Fatal("decode error 1:", err)
            }
            fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y)
            err = dec.Decode(&q)
            if err != nil {
                log.Fatal("decode error 2:", err)
            }
            fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y)
        
            // Output:
            // "Pythagoras": {3, 4}
            // "Treehouse": {1782, 1841}
        }
        

        Example (EncodeDecode)

        This example transmits a value that implements the custom encoding and decoding methods.

        Code:

        package gob_test
        
        import (
            "bytes"
            "encoding/gob"
            "fmt"
            "log"
        )
        
        // The Vector type has unexported fields, which the package cannot access.
        // We therefore write a BinaryMarshal/BinaryUnmarshal method pair to allow us
        // to send and receive the type with the gob package. These interfaces are
        // defined in the "encoding" package.
        // We could equivalently use the locally defined GobEncode/GobDecoder
        // interfaces.
        type Vector struct {
            x, y, z int
        }
        
        func (v Vector) MarshalBinary() ([]byte, error) {
            // A simple encoding: plain text.
            var b bytes.Buffer
            fmt.Fprintln(&b, v.x, v.y, v.z)
            return b.Bytes(), nil
        }
        
        // UnmarshalBinary modifies the receiver so it must take a pointer receiver.
        func (v *Vector) UnmarshalBinary(data []byte) error {
            // A simple encoding: plain text.
            b := bytes.NewBuffer(data)
            _, err := fmt.Fscanln(b, &v.x, &v.y, &v.z)
            return err
        }
        
        // This example transmits a value that implements the custom encoding and decoding methods.
        func Example_encodeDecode() {
            var network bytes.Buffer // Stand-in for the network.
        
            // Create an encoder and send a value.
            enc := gob.NewEncoder(&network)
            err := enc.Encode(Vector{3, 4, 5})
            if err != nil {
                log.Fatal("encode:", err)
            }
        
            // Create a decoder and receive a value.
            dec := gob.NewDecoder(&network)
            var v Vector
            err = dec.Decode(&v)
            if err != nil {
                log.Fatal("decode:", err)
            }
            fmt.Println(v)
        
            // Output:
            // {3 4 5}
        }
        

        Example (Interface)

        This example shows how to encode an interface value. The key distinction from regular types is to register the concrete type that implements the interface.

        Code:

        package gob_test
        
        import (
            "bytes"
            "encoding/gob"
            "fmt"
            "log"
            "math"
        )
        
        type Point struct {
            X, Y int
        }
        
        func (p Point) Hypotenuse() float64 {
            return math.Hypot(float64(p.X), float64(p.Y))
        }
        
        type Pythagoras interface {
            Hypotenuse() float64
        }
        
        // This example shows how to encode an interface value. The key
        // distinction from regular types is to register the concrete type that
        // implements the interface.
        func Example_interface() {
            var network bytes.Buffer // Stand-in for the network.
        
            // We must register the concrete type for the encoder and decoder (which would
            // normally be on a separate machine from the encoder). On each end, this tells the
            // engine which concrete type is being sent that implements the interface.
            gob.Register(Point{})
        
            // Create an encoder and send some values.
            enc := gob.NewEncoder(&network)
            for i := 1; i <= 3; i++ {
                interfaceEncode(enc, Point{3 * i, 4 * i})
            }
        
            // Create a decoder and receive some values.
            dec := gob.NewDecoder(&network)
            for i := 1; i <= 3; i++ {
                result := interfaceDecode(dec)
                fmt.Println(result.Hypotenuse())
            }
        
            // Output:
            // 5
            // 10
            // 15
        }
        
        // interfaceEncode encodes the interface value into the encoder.
        func interfaceEncode(enc *gob.Encoder, p Pythagoras) {
            // The encode will fail unless the concrete type has been
            // registered. We registered it in the calling function.
        
            // Pass pointer to interface so Encode sees (and hence sends) a value of
            // interface type. If we passed p directly it would see the concrete type instead.
            // See the blog post, "The Laws of Reflection" for background.
            err := enc.Encode(&p)
            if err != nil {
                log.Fatal("encode:", err)
            }
        }
        
        // interfaceDecode decodes the next interface value from the stream and returns it.
        func interfaceDecode(dec *gob.Decoder) Pythagoras {
            // The decode will fail unless the concrete type on the wire has been
            // registered. We registered it in the calling function.
            var p Pythagoras
            err := dec.Decode(&p)
            if err != nil {
                log.Fatal("decode:", err)
            }
            return p
        }
        

        func Register

        func Register(value any)

        Register records a type, identified by a value for that type, under its internal type name. That name will identify the concrete type of a value sent or received as an interface variable. Only types that will be transferred as implementations of interface values need to be registered. Expecting to be used only during initialization, it panics if the mapping between types and names is not a bijection.

        func RegisterName

        func RegisterName(name string, value any)

        RegisterName is like Register but uses the provided name rather than the type's default.

        type CommonType

        CommonType holds elements of all types. It is a historical artifact, kept for binary compatibility and exported only for the benefit of the package's encoding of type descriptors. It is not intended for direct use by clients.

        type CommonType struct {
            Name string
            Id   typeId
        }
        

        type Decoder

        A Decoder manages the receipt of type and data information read from the remote side of a connection. It is safe for concurrent use by multiple goroutines.

        The Decoder does only basic sanity checking on decoded input sizes, and its limits are not configurable. Take caution when decoding gob data from untrusted sources.

        type Decoder struct {
            // contains filtered or unexported fields
        }
        

        func NewDecoder

        func NewDecoder(r io.Reader) *Decoder

        NewDecoder returns a new decoder that reads from the io.Reader. If r does not also implement io.ByteReader, it will be wrapped in a bufio.Reader.

        func (*Decoder) Decode

        func (dec *Decoder) Decode(e any) error

        Decode reads the next value from the input stream and stores it in the data represented by the empty interface value. If e is nil, the value will be discarded. Otherwise, the value underlying e must be a pointer to the correct type for the next data item received. If the input is at EOF, Decode returns io.EOF and does not modify e.

        func (*Decoder) DecodeValue

        func (dec *Decoder) DecodeValue(v reflect.Value) error

        DecodeValue reads the next value from the input stream. If v is the zero reflect.Value (v.Kind() == Invalid), DecodeValue discards the value. Otherwise, it stores the value into v. In that case, v must represent a non-nil pointer to data or be an assignable reflect.Value (v.CanSet()) If the input is at EOF, DecodeValue returns io.EOF and does not modify v.

        type Encoder

        An Encoder manages the transmission of type and data information to the other side of a connection. It is safe for concurrent use by multiple goroutines.

        type Encoder struct {
            // contains filtered or unexported fields
        }
        

        func NewEncoder

        func NewEncoder(w io.Writer) *Encoder

        NewEncoder returns a new encoder that will transmit on the io.Writer.

        func (*Encoder) Encode

        func (enc *Encoder) Encode(e any) error

        Encode transmits the data item represented by the empty interface value, guaranteeing that all necessary type information has been transmitted first. Passing a nil pointer to Encoder will panic, as they cannot be transmitted by gob.

        func (*Encoder) EncodeValue

        func (enc *Encoder) EncodeValue(value reflect.Value) error

        EncodeValue transmits the data item represented by the reflection value, guaranteeing that all necessary type information has been transmitted first. Passing a nil pointer to EncodeValue will panic, as they cannot be transmitted by gob.

        type GobDecoder

        GobDecoder is the interface describing data that provides its own routine for decoding transmitted values sent by a GobEncoder.

        type GobDecoder interface {
            // GobDecode overwrites the receiver, which must be a pointer,
            // with the value represented by the byte slice, which was written
            // by GobEncode, usually for the same concrete type.
            GobDecode([]byte) error
        }

        type GobEncoder

        GobEncoder is the interface describing data that provides its own representation for encoding values for transmission to a GobDecoder. A type that implements GobEncoder and GobDecoder has complete control over the representation of its data and may therefore contain things such as private fields, channels, and functions, which are not usually transmissible in gob streams.

        Note: Since gobs can be stored permanently, it is good design to guarantee the encoding used by a GobEncoder is stable as the software evolves. For instance, it might make sense for GobEncode to include a version number in the encoding.

        type GobEncoder interface {
            // GobEncode returns a byte slice representing the encoding of the
            // receiver for transmission to a GobDecoder, usually of the same
            // concrete type.
            GobEncode() ([]byte, error)
        }
        hex - Go Documentation Server
        ...

        Package hex

        import "encoding/hex"
        Overview
        Index
        Examples

        Overview ▾

        Package hex implements hexadecimal encoding and decoding.

        Variables

        ErrLength reports an attempt to decode an odd-length input using Decode or DecodeString. The stream-based Decoder returns io.ErrUnexpectedEOF instead of ErrLength.

        var ErrLength = errors.New("encoding/hex: odd length hex string")

        func AppendDecode

        func AppendDecode(dst, src []byte) ([]byte, error)

        AppendDecode appends the hexadecimally decoded src to dst and returns the extended buffer. If the input is malformed, it returns the partially decoded src and an error.

        func AppendEncode

        func AppendEncode(dst, src []byte) []byte

        AppendEncode appends the hexadecimally encoded src to dst and returns the extended buffer.

        func Decode

        func Decode(dst, src []byte) (int, error)

        Decode decodes src into DecodedLen(len(src)) bytes, returning the actual number of bytes written to dst.

        Decode expects that src contains only hexadecimal characters and that src has even length. If the input is malformed, Decode returns the number of bytes decoded before the error.

        Example

        Code:

        src := []byte("48656c6c6f20476f7068657221")
        
        dst := make([]byte, hex.DecodedLen(len(src)))
        n, err := hex.Decode(dst, src)
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%s\n", dst[:n])
        
        

        Output:

        Hello Gopher!
        

        func DecodeString

        func DecodeString(s string) ([]byte, error)

        DecodeString returns the bytes represented by the hexadecimal string s.

        DecodeString expects that src contains only hexadecimal characters and that src has even length. If the input is malformed, DecodeString returns the bytes decoded before the error.

        Example

        Code:

        const s = "48656c6c6f20476f7068657221"
        decoded, err := hex.DecodeString(s)
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%s\n", decoded)
        
        

        Output:

        Hello Gopher!
        

        func DecodedLen

        func DecodedLen(x int) int

        DecodedLen returns the length of a decoding of x source bytes. Specifically, it returns x / 2.

        func Dump

        func Dump(data []byte) string

        Dump returns a string that contains a hex dump of the given data. The format of the hex dump matches the output of `hexdump -C` on the command line.

        Example

        Code:

        content := []byte("Go is an open source programming language.")
        
        fmt.Printf("%s", hex.Dump(content))
        
        

        Output:

        00000000  47 6f 20 69 73 20 61 6e  20 6f 70 65 6e 20 73 6f  |Go is an open so|
        00000010  75 72 63 65 20 70 72 6f  67 72 61 6d 6d 69 6e 67  |urce programming|
        00000020  20 6c 61 6e 67 75 61 67  65 2e                    | language.|
        

        func Dumper

        func Dumper(w io.Writer) io.WriteCloser

        Dumper returns a io.WriteCloser that writes a hex dump of all written data to w. The format of the dump matches the output of `hexdump -C` on the command line.

        Example

        Code:

        lines := []string{
            "Go is an open source programming language.",
            "\n",
            "We encourage all Go users to subscribe to golang-announce.",
        }
        
        stdoutDumper := hex.Dumper(os.Stdout)
        
        defer stdoutDumper.Close()
        
        for _, line := range lines {
            stdoutDumper.Write([]byte(line))
        }
        
        

        Output:

        00000000  47 6f 20 69 73 20 61 6e  20 6f 70 65 6e 20 73 6f  |Go is an open so|
        00000010  75 72 63 65 20 70 72 6f  67 72 61 6d 6d 69 6e 67  |urce programming|
        00000020  20 6c 61 6e 67 75 61 67  65 2e 0a 57 65 20 65 6e  | language..We en|
        00000030  63 6f 75 72 61 67 65 20  61 6c 6c 20 47 6f 20 75  |courage all Go u|
        00000040  73 65 72 73 20 74 6f 20  73 75 62 73 63 72 69 62  |sers to subscrib|
        00000050  65 20 74 6f 20 67 6f 6c  61 6e 67 2d 61 6e 6e 6f  |e to golang-anno|
        00000060  75 6e 63 65 2e                                    |unce.|
        

        func Encode

        func Encode(dst, src []byte) int

        Encode encodes src into EncodedLen(len(src)) bytes of dst. As a convenience, it returns the number of bytes written to dst, but this value is always EncodedLen(len(src)). Encode implements hexadecimal encoding.

        Example

        Code:

        src := []byte("Hello Gopher!")
        
        dst := make([]byte, hex.EncodedLen(len(src)))
        hex.Encode(dst, src)
        
        fmt.Printf("%s\n", dst)
        
        

        Output:

        48656c6c6f20476f7068657221
        

        func EncodeToString

        func EncodeToString(src []byte) string

        EncodeToString returns the hexadecimal encoding of src.

        Example

        Code:

        src := []byte("Hello")
        encodedStr := hex.EncodeToString(src)
        
        fmt.Printf("%s\n", encodedStr)
        
        

        Output:

        48656c6c6f
        

        func EncodedLen

        func EncodedLen(n int) int

        EncodedLen returns the length of an encoding of n source bytes. Specifically, it returns n * 2.

        func NewDecoder

        func NewDecoder(r io.Reader) io.Reader

        NewDecoder returns an io.Reader that decodes hexadecimal characters from r. NewDecoder expects that r contain only an even number of hexadecimal characters.

        func NewEncoder

        func NewEncoder(w io.Writer) io.Writer

        NewEncoder returns an io.Writer that writes lowercase hexadecimal characters to w.

        type InvalidByteError

        InvalidByteError values describe errors resulting from an invalid byte in a hex string.

        type InvalidByteError byte

        func (InvalidByteError) Error

        func (e InvalidByteError) Error() string
        json - Go Documentation Server
        ...

        Package json

        import "encoding/json"
        Overview
        Index
        Examples

        Overview ▾

        Package json implements encoding and decoding of JSON as defined in RFC 7159. The mapping between JSON and Go values is described in the documentation for the Marshal and Unmarshal functions.

        See "JSON and Go" for an introduction to this package: https://golang.org/doc/articles/json_and_go.html

        Example (CustomMarshalJSON)

        Code:

        package json_test
        
        import (
            "encoding/json"
            "fmt"
            "log"
            "strings"
        )
        
        type Animal int
        
        const (
            Unknown Animal = iota
            Gopher
            Zebra
        )
        
        func (a *Animal) UnmarshalJSON(b []byte) error {
            var s string
            if err := json.Unmarshal(b, &s); err != nil {
                return err
            }
            switch strings.ToLower(s) {
            default:
                *a = Unknown
            case "gopher":
                *a = Gopher
            case "zebra":
                *a = Zebra
            }
        
            return nil
        }
        
        func (a Animal) MarshalJSON() ([]byte, error) {
            var s string
            switch a {
            default:
                s = "unknown"
            case Gopher:
                s = "gopher"
            case Zebra:
                s = "zebra"
            }
        
            return json.Marshal(s)
        }
        
        func Example_customMarshalJSON() {
            blob := `["gopher","armadillo","zebra","unknown","gopher","bee","gopher","zebra"]`
            var zoo []Animal
            if err := json.Unmarshal([]byte(blob), &zoo); err != nil {
                log.Fatal(err)
            }
        
            census := make(map[Animal]int)
            for _, animal := range zoo {
                census[animal] += 1
            }
        
            fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras:  %d\n* Unknown: %d\n",
                census[Gopher], census[Zebra], census[Unknown])
        
            // Output:
            // Zoo Census:
            // * Gophers: 3
            // * Zebras:  2
            // * Unknown: 3
        }
        

        Example (TextMarshalJSON)

        Code:

        package json_test
        
        import (
            "encoding/json"
            "fmt"
            "log"
            "strings"
        )
        
        type Size int
        
        const (
            Unrecognized Size = iota
            Small
            Large
        )
        
        func (s *Size) UnmarshalText(text []byte) error {
            switch strings.ToLower(string(text)) {
            default:
                *s = Unrecognized
            case "small":
                *s = Small
            case "large":
                *s = Large
            }
            return nil
        }
        
        func (s Size) MarshalText() ([]byte, error) {
            var name string
            switch s {
            default:
                name = "unrecognized"
            case Small:
                name = "small"
            case Large:
                name = "large"
            }
            return []byte(name), nil
        }
        
        func Example_textMarshalJSON() {
            blob := `["small","regular","large","unrecognized","small","normal","small","large"]`
            var inventory []Size
            if err := json.Unmarshal([]byte(blob), &inventory); err != nil {
                log.Fatal(err)
            }
        
            counts := make(map[Size]int)
            for _, size := range inventory {
                counts[size] += 1
            }
        
            fmt.Printf("Inventory Counts:\n* Small:        %d\n* Large:        %d\n* Unrecognized: %d\n",
                counts[Small], counts[Large], counts[Unrecognized])
        
            // Output:
            // Inventory Counts:
            // * Small:        3
            // * Large:        2
            // * Unrecognized: 3
        }
        

        Index ▾

        func Compact(dst *bytes.Buffer, src []byte) error
        func HTMLEscape(dst *bytes.Buffer, src []byte)
        func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
        func Marshal(v any) ([]byte, error)
        func MarshalIndent(v any, prefix, indent string) ([]byte, error)
        func Unmarshal(data []byte, v any) error
        func Valid(data []byte) bool
        type Decoder
            func NewDecoder(r io.Reader) *Decoder
            func (dec *Decoder) Buffered() io.Reader
            func (dec *Decoder) Decode(v any) error
            func (dec *Decoder) DisallowUnknownFields()
            func (dec *Decoder) InputOffset() int64
            func (dec *Decoder) More() bool
            func (dec *Decoder) Token() (Token, error)
            func (dec *Decoder) UseNumber()
        type Delim
            func (d Delim) String() string
        type Encoder
            func NewEncoder(w io.Writer) *Encoder
            func (enc *Encoder) Encode(v any) error
            func (enc *Encoder) SetEscapeHTML(on bool)
            func (enc *Encoder) SetIndent(prefix, indent string)
        type InvalidUTF8Error
            func (e *InvalidUTF8Error) Error() string
        type InvalidUnmarshalError
            func (e *InvalidUnmarshalError) Error() string
        type Marshaler
        type MarshalerError
            func (e *MarshalerError) Error() string
            func (e *MarshalerError) Unwrap() error
        type Number
            func (n Number) Float64() (float64, error)
            func (n Number) Int64() (int64, error)
            func (n Number) String() string
        type RawMessage
            func (m RawMessage) MarshalJSON() ([]byte, error)
            func (m *RawMessage) UnmarshalJSON(data []byte) error
        type SyntaxError
            func (e *SyntaxError) Error() string
        type Token
        type UnmarshalFieldError
            func (e *UnmarshalFieldError) Error() string
        type UnmarshalTypeError
            func (e *UnmarshalTypeError) Error() string
        type Unmarshaler
        type UnsupportedTypeError
            func (e *UnsupportedTypeError) Error() string
        type UnsupportedValueError
            func (e *UnsupportedValueError) Error() string

        Package files

        decode.go encode.go fold.go indent.go scanner.go stream.go tables.go tags.go

        func Compact

        func Compact(dst *bytes.Buffer, src []byte) error

        Compact appends to dst the JSON-encoded src with insignificant space characters elided.

        func HTMLEscape

        func HTMLEscape(dst *bytes.Buffer, src []byte)

        HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 so that the JSON will be safe to embed inside HTML <script> tags. For historical reasons, web browsers don't honor standard HTML escaping within <script> tags, so an alternative JSON encoding must be used.

        Example

        Code:

        var out bytes.Buffer
        json.HTMLEscape(&out, []byte(`{"Name":"<b>HTML content</b>"}`))
        out.WriteTo(os.Stdout)
        

        Output:

        {"Name":"\u003cb\u003eHTML content\u003c/b\u003e"}
        

        func Indent

        func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error

        Indent appends to dst an indented form of the JSON-encoded src. Each element in a JSON object or array begins on a new, indented line beginning with prefix followed by one or more copies of indent according to the indentation nesting. The data appended to dst does not begin with the prefix nor any indentation, to make it easier to embed inside other formatted JSON data. Although leading space characters (space, tab, carriage return, newline) at the beginning of src are dropped, trailing space characters at the end of src are preserved and copied to dst. For example, if src has no trailing spaces, neither will dst; if src ends in a trailing newline, so will dst.

        Example

        Code:

        type Road struct {
            Name   string
            Number int
        }
        roads := []Road{
            {"Diamond Fork", 29},
            {"Sheep Creek", 51},
        }
        
        b, err := json.Marshal(roads)
        if err != nil {
            log.Fatal(err)
        }
        
        var out bytes.Buffer
        json.Indent(&out, b, "=", "\t")
        out.WriteTo(os.Stdout)
        

        Output:

        [
        =	{
        =		"Name": "Diamond Fork",
        =		"Number": 29
        =	},
        =	{
        =		"Name": "Sheep Creek",
        =		"Number": 51
        =	}
        =]
        

        func Marshal

        func Marshal(v any) ([]byte, error)

        Marshal returns the JSON encoding of v.

        Marshal traverses the value v recursively. If an encountered value implements Marshaler and is not a nil pointer, Marshal calls [Marshaler.MarshalJSON] to produce JSON. If no [Marshaler.MarshalJSON] method is present but the value implements encoding.TextMarshaler instead, Marshal calls encoding.TextMarshaler.MarshalText and encodes the result as a JSON string. The nil pointer exception is not strictly necessary but mimics a similar, necessary exception in the behavior of [Unmarshaler.UnmarshalJSON].

        Otherwise, Marshal uses the following type-dependent default encodings:

        Boolean values encode as JSON booleans.

        Floating point, integer, and Number values encode as JSON numbers. NaN and +/-Inf values will return an UnsupportedValueError.

        String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. So that the JSON will be safe to embed inside HTML <script> tags, the string is encoded using HTMLEscape, which replaces "<", ">", "&", U+2028, and U+2029 are escaped to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029". This replacement can be disabled when using an Encoder, by calling Encoder.SetEscapeHTML(false).

        Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

        Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below.

        The encoding of each struct field can be customized by the format string stored under the "json" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name.

        The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

        As a special case, if the field tag is "-", the field is always omitted. Note that a field with name "-" can still be generated using the tag "-,".

        Examples of struct field tags and their meanings:

        // Field appears in JSON as key "myName".
        Field int `json:"myName"`
        
        // Field appears in JSON as key "myName" and
        // the field is omitted from the object if its value is empty,
        // as defined above.
        Field int `json:"myName,omitempty"`
        
        // Field appears in JSON as key "Field" (the default), but
        // the field is skipped if empty.
        // Note the leading comma.
        Field int `json:",omitempty"`
        
        // Field is ignored by this package.
        Field int `json:"-"`
        
        // Field appears in JSON as key "-".
        Field int `json:"-,"`
        

        The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:

        Int64String int64 `json:",string"`
        

        The key name will be used if it's a non-empty string consisting of only Unicode letters, digits, and ASCII punctuation except quotation marks, backslash, and comma.

        Embedded struct fields are usually marshaled as if their inner exported fields were fields in the outer struct, subject to the usual Go visibility rules amended as described in the next paragraph. An anonymous struct field with a name given in its JSON tag is treated as having that name, rather than being anonymous. An anonymous struct field of interface type is treated the same as having that type as its name, rather than being anonymous.

        The Go visibility rules for struct fields are amended for JSON when deciding which field to marshal or unmarshal. If there are multiple fields at the same level, and that level is the least nested (and would therefore be the nesting level selected by the usual Go rules), the following extra rules apply:

        1) Of those fields, if any are JSON-tagged, only tagged fields are considered, even if there are multiple untagged fields that would otherwise conflict.

        2) If there is exactly one field (tagged or not according to the first rule), that is selected.

        3) Otherwise there are multiple fields, and all are ignored; no error occurs.

        Handling of anonymous struct fields is new in Go 1.1. Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of an anonymous struct field in both current and earlier versions, give the field a JSON tag of "-".

        Map values encode as JSON objects. The map's key type must either be a string, an integer type, or implement encoding.TextMarshaler. The map keys are sorted and used as JSON object keys by applying the following rules, subject to the UTF-8 coercion described for string values above:

        • keys of any string type are used directly
        • encoding.TextMarshalers are marshaled
        • integer keys are converted to strings

        Pointer values encode as the value pointed to. A nil pointer encodes as the null JSON value.

        Interface values encode as the value contained in the interface. A nil interface value encodes as the null JSON value.

        Channel, complex, and function values cannot be encoded in JSON. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError.

        JSON cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an error.

        Example

        Code:

        type ColorGroup struct {
            ID     int
            Name   string
            Colors []string
        }
        group := ColorGroup{
            ID:     1,
            Name:   "Reds",
            Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
        }
        b, err := json.Marshal(group)
        if err != nil {
            fmt.Println("error:", err)
        }
        os.Stdout.Write(b)
        

        Output:

        {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
        

        func MarshalIndent

        func MarshalIndent(v any, prefix, indent string) ([]byte, error)

        MarshalIndent is like Marshal but applies Indent to format the output. Each JSON element in the output will begin on a new line beginning with prefix followed by one or more copies of indent according to the indentation nesting.

        Example

        Code:

        data := map[string]int{
            "a": 1,
            "b": 2,
        }
        
        b, err := json.MarshalIndent(data, "<prefix>", "<indent>")
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Println(string(b))
        

        Output:

        {
        <prefix><indent>"a": 1,
        <prefix><indent>"b": 2
        <prefix>}
        

        func Unmarshal

        func Unmarshal(data []byte, v any) error

        Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

        Unmarshal uses the inverse of the encodings that Marshal uses, allocating maps, slices, and pointers as necessary, with the following additional rules:

        To unmarshal JSON into a pointer, Unmarshal first handles the case of the JSON being the JSON literal null. In that case, Unmarshal sets the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into the value pointed at by the pointer. If the pointer is nil, Unmarshal allocates a new value for it to point to.

        To unmarshal JSON into a value implementing Unmarshaler, Unmarshal calls that value's [Unmarshaler.UnmarshalJSON] method, including when the input is a JSON null. Otherwise, if the value implements encoding.TextUnmarshaler and the input is a JSON quoted string, Unmarshal calls encoding.TextUnmarshaler.UnmarshalText with the unquoted form of the string.

        To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. By default, object keys which don't have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).

        To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

        • bool, for JSON booleans
        • float64, for JSON numbers
        • string, for JSON strings
        • []interface{}, for JSON arrays
        • map[string]interface{}, for JSON objects
        • nil for JSON null

        To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice.

        To unmarshal a JSON array into a Go array, Unmarshal decodes JSON array elements into corresponding Go array elements. If the Go array is smaller than the JSON array, the additional JSON array elements are discarded. If the JSON array is smaller than the Go array, the additional Go array elements are set to zero values.

        To unmarshal a JSON object into a map, Unmarshal first establishes a map to use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal reuses the existing map, keeping existing entries. Unmarshal then stores key-value pairs from the JSON object into the map. The map's key type must either be any string type, an integer, implement json.Unmarshaler, or implement encoding.TextUnmarshaler.

        If the JSON-encoded data contain a syntax error, Unmarshal returns a SyntaxError.

        If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, Unmarshal skips that field and completes the unmarshaling as best it can. If no more serious errors are encountered, Unmarshal returns an UnmarshalTypeError describing the earliest such error. In any case, it's not guaranteed that all the remaining fields following the problematic one will be unmarshaled into the target object.

        The JSON null value unmarshals into an interface, map, pointer, or slice by setting that Go value to nil. Because null is often used in JSON to mean “not present,” unmarshaling a JSON null into any other Go type has no effect on the value and produces no error.

        When unmarshaling quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD.

        Example

        Code:

        var jsonBlob = []byte(`[
            {"Name": "Platypus", "Order": "Monotremata"},
            {"Name": "Quoll",    "Order": "Dasyuromorphia"}
        ]`)
        type Animal struct {
            Name  string
            Order string
        }
        var animals []Animal
        err := json.Unmarshal(jsonBlob, &animals)
        if err != nil {
            fmt.Println("error:", err)
        }
        fmt.Printf("%+v", animals)
        

        Output:

        [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
        

        func Valid

        func Valid(data []byte) bool

        Valid reports whether data is a valid JSON encoding.

        Example

        Code:

        goodJSON := `{"example": 1}`
        badJSON := `{"example":2:]}}`
        
        fmt.Println(json.Valid([]byte(goodJSON)), json.Valid([]byte(badJSON)))
        

        Output:

        true false
        

        type Decoder

        A Decoder reads and decodes JSON values from an input stream.

        type Decoder struct {
            // contains filtered or unexported fields
        }
        

        Example

        This example uses a Decoder to decode a stream of distinct JSON values.

        Code:

        const jsonStream = `
            {"Name": "Ed", "Text": "Knock knock."}
            {"Name": "Sam", "Text": "Who's there?"}
            {"Name": "Ed", "Text": "Go fmt."}
            {"Name": "Sam", "Text": "Go fmt who?"}
            {"Name": "Ed", "Text": "Go fmt yourself!"}
        `
        type Message struct {
            Name, Text string
        }
        dec := json.NewDecoder(strings.NewReader(jsonStream))
        for {
            var m Message
            if err := dec.Decode(&m); err == io.EOF {
                break
            } else if err != nil {
                log.Fatal(err)
            }
            fmt.Printf("%s: %s\n", m.Name, m.Text)
        }
        

        Output:

        Ed: Knock knock.
        Sam: Who's there?
        Ed: Go fmt.
        Sam: Go fmt who?
        Ed: Go fmt yourself!
        

        func NewDecoder

        func NewDecoder(r io.Reader) *Decoder

        NewDecoder returns a new decoder that reads from r.

        The decoder introduces its own buffering and may read data from r beyond the JSON values requested.

        func (*Decoder) Buffered

        func (dec *Decoder) Buffered() io.Reader

        Buffered returns a reader of the data remaining in the Decoder's buffer. The reader is valid until the next call to Decoder.Decode.

        func (*Decoder) Decode

        func (dec *Decoder) Decode(v any) error

        Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.

        See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

        Example (Stream)

        This example uses a Decoder to decode a streaming array of JSON objects.

        Code:

        const jsonStream = `
            [
                {"Name": "Ed", "Text": "Knock knock."},
                {"Name": "Sam", "Text": "Who's there?"},
                {"Name": "Ed", "Text": "Go fmt."},
                {"Name": "Sam", "Text": "Go fmt who?"},
                {"Name": "Ed", "Text": "Go fmt yourself!"}
            ]
        `
        type Message struct {
            Name, Text string
        }
        dec := json.NewDecoder(strings.NewReader(jsonStream))
        
        // read open bracket
        t, err := dec.Token()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%T: %v\n", t, t)
        
        // while the array contains values
        for dec.More() {
            var m Message
            // decode an array value (Message)
            err := dec.Decode(&m)
            if err != nil {
                log.Fatal(err)
            }
        
            fmt.Printf("%v: %v\n", m.Name, m.Text)
        }
        
        // read closing bracket
        t, err = dec.Token()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%T: %v\n", t, t)
        
        

        Output:

        json.Delim: [
        Ed: Knock knock.
        Sam: Who's there?
        Ed: Go fmt.
        Sam: Go fmt who?
        Ed: Go fmt yourself!
        json.Delim: ]
        

        func (*Decoder) DisallowUnknownFields

        func (dec *Decoder) DisallowUnknownFields()

        DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.

        func (*Decoder) InputOffset

        func (dec *Decoder) InputOffset() int64

        InputOffset returns the input stream byte offset of the current decoder position. The offset gives the location of the end of the most recently returned token and the beginning of the next token.

        func (*Decoder) More

        func (dec *Decoder) More() bool

        More reports whether there is another element in the current array or object being parsed.

        func (*Decoder) Token

        func (dec *Decoder) Token() (Token, error)

        Token returns the next JSON token in the input stream. At the end of the input stream, Token returns nil, io.EOF.

        Token guarantees that the delimiters [ ] { } it returns are properly nested and matched: if Token encounters an unexpected delimiter in the input, it will return an error.

        The input stream consists of basic JSON values—bool, string, number, and null—along with delimiters [ ] { } of type Delim to mark the start and end of arrays and objects. Commas and colons are elided.

        Example

        This example uses a Decoder to decode a stream of distinct JSON values.

        Code:

        const jsonStream = `
            {"Message": "Hello", "Array": [1, 2, 3], "Null": null, "Number": 1.234}
        `
        dec := json.NewDecoder(strings.NewReader(jsonStream))
        for {
            t, err := dec.Token()
            if err == io.EOF {
                break
            }
            if err != nil {
                log.Fatal(err)
            }
            fmt.Printf("%T: %v", t, t)
            if dec.More() {
                fmt.Printf(" (more)")
            }
            fmt.Printf("\n")
        }
        

        Output:

        json.Delim: { (more)
        string: Message (more)
        string: Hello (more)
        string: Array (more)
        json.Delim: [ (more)
        float64: 1 (more)
        float64: 2 (more)
        float64: 3
        json.Delim: ] (more)
        string: Null (more)
        <nil>: <nil> (more)
        string: Number (more)
        float64: 1.234
        json.Delim: }
        

        func (*Decoder) UseNumber

        func (dec *Decoder) UseNumber()

        UseNumber causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.

        type Delim

        A Delim is a JSON array or object delimiter, one of [ ] { or }.

        type Delim rune

        func (Delim) String

        func (d Delim) String() string

        type Encoder

        An Encoder writes JSON values to an output stream.

        type Encoder struct {
            // contains filtered or unexported fields
        }
        

        func NewEncoder

        func NewEncoder(w io.Writer) *Encoder

        NewEncoder returns a new encoder that writes to w.

        func (*Encoder) Encode

        func (enc *Encoder) Encode(v any) error

        Encode writes the JSON encoding of v to the stream, followed by a newline character.

        See the documentation for Marshal for details about the conversion of Go values to JSON.

        func (*Encoder) SetEscapeHTML

        func (enc *Encoder) SetEscapeHTML(on bool)

        SetEscapeHTML specifies whether problematic HTML characters should be escaped inside JSON quoted strings. The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.

        In non-HTML settings where the escaping interferes with the readability of the output, SetEscapeHTML(false) disables this behavior.

        func (*Encoder) SetIndent

        func (enc *Encoder) SetIndent(prefix, indent string)

        SetIndent instructs the encoder to format each subsequent encoded value as if indented by the package-level function Indent(dst, src, prefix, indent). Calling SetIndent("", "") disables indentation.

        type InvalidUTF8Error

        Before Go 1.2, an InvalidUTF8Error was returned by Marshal when attempting to encode a string value with invalid UTF-8 sequences. As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by replacing invalid bytes with the Unicode replacement rune U+FFFD.

        Deprecated: No longer used; kept for compatibility.

        type InvalidUTF8Error struct {
            S string // the whole string value that caused the error
        }
        

        func (*InvalidUTF8Error) Error

        func (e *InvalidUTF8Error) Error() string

        type InvalidUnmarshalError

        An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil pointer.)

        type InvalidUnmarshalError struct {
            Type reflect.Type
        }
        

        func (*InvalidUnmarshalError) Error

        func (e *InvalidUnmarshalError) Error() string

        type Marshaler

        Marshaler is the interface implemented by types that can marshal themselves into valid JSON.

        type Marshaler interface {
            MarshalJSON() ([]byte, error)
        }

        type MarshalerError

        A MarshalerError represents an error from calling a [Marshaler.MarshalJSON] or encoding.TextMarshaler.MarshalText method.

        type MarshalerError struct {
            Type reflect.Type
            Err  error
            // contains filtered or unexported fields
        }
        

        func (*MarshalerError) Error

        func (e *MarshalerError) Error() string

        func (*MarshalerError) Unwrap

        func (e *MarshalerError) Unwrap() error

        Unwrap returns the underlying error.

        type Number

        A Number represents a JSON number literal.

        type Number string

        func (Number) Float64

        func (n Number) Float64() (float64, error)

        Float64 returns the number as a float64.

        func (Number) Int64

        func (n Number) Int64() (int64, error)

        Int64 returns the number as an int64.

        func (Number) String

        func (n Number) String() string

        String returns the literal text of the number.

        type RawMessage

        RawMessage is a raw encoded JSON value. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.

        type RawMessage []byte

        Example (Marshal)

        This example uses RawMessage to use a precomputed JSON during marshal.

        Code:

        h := json.RawMessage(`{"precomputed": true}`)
        
        c := struct {
            Header *json.RawMessage `json:"header"`
            Body   string           `json:"body"`
        }{Header: &h, Body: "Hello Gophers!"}
        
        b, err := json.MarshalIndent(&c, "", "\t")
        if err != nil {
            fmt.Println("error:", err)
        }
        os.Stdout.Write(b)
        
        

        Output:

        {
        	"header": {
        		"precomputed": true
        	},
        	"body": "Hello Gophers!"
        }
        

        Example (Unmarshal)

        This example uses RawMessage to delay parsing part of a JSON message.

        Code:

        type Color struct {
            Space string
            Point json.RawMessage // delay parsing until we know the color space
        }
        type RGB struct {
            R uint8
            G uint8
            B uint8
        }
        type YCbCr struct {
            Y  uint8
            Cb int8
            Cr int8
        }
        
        var j = []byte(`[
            {"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
            {"Space": "RGB",   "Point": {"R": 98, "G": 218, "B": 255}}
        ]`)
        var colors []Color
        err := json.Unmarshal(j, &colors)
        if err != nil {
            log.Fatalln("error:", err)
        }
        
        for _, c := range colors {
            var dst any
            switch c.Space {
            case "RGB":
                dst = new(RGB)
            case "YCbCr":
                dst = new(YCbCr)
            }
            err := json.Unmarshal(c.Point, dst)
            if err != nil {
                log.Fatalln("error:", err)
            }
            fmt.Println(c.Space, dst)
        }
        

        Output:

        YCbCr &{255 0 -10}
        RGB &{98 218 255}
        

        func (RawMessage) MarshalJSON

        func (m RawMessage) MarshalJSON() ([]byte, error)

        MarshalJSON returns m as the JSON encoding of m.

        func (*RawMessage) UnmarshalJSON

        func (m *RawMessage) UnmarshalJSON(data []byte) error

        UnmarshalJSON sets *m to a copy of data.

        type SyntaxError

        A SyntaxError is a description of a JSON syntax error. Unmarshal will return a SyntaxError if the JSON can't be parsed.

        type SyntaxError struct {
            Offset int64 // error occurred after reading Offset bytes
            // contains filtered or unexported fields
        }
        

        func (*SyntaxError) Error

        func (e *SyntaxError) Error() string

        type Token

        A Token holds a value of one of these types:

        • Delim, for the four JSON delimiters [ ] { }
        • bool, for JSON booleans
        • float64, for JSON numbers
        • Number, for JSON numbers
        • string, for JSON string literals
        • nil, for JSON null
        type Token any

        type UnmarshalFieldError

        An UnmarshalFieldError describes a JSON object key that led to an unexported (and therefore unwritable) struct field.

        Deprecated: No longer used; kept for compatibility.

        type UnmarshalFieldError struct {
            Key   string
            Type  reflect.Type
            Field reflect.StructField
        }
        

        func (*UnmarshalFieldError) Error

        func (e *UnmarshalFieldError) Error() string

        type UnmarshalTypeError

        An UnmarshalTypeError describes a JSON value that was not appropriate for a value of a specific Go type.

        type UnmarshalTypeError struct {
            Value  string       // description of JSON value - "bool", "array", "number -5"
            Type   reflect.Type // type of Go value it could not be assigned to
            Offset int64        // error occurred after reading Offset bytes
            Struct string       // name of the struct type containing the field
            Field  string       // the full path from root node to the field
        }
        

        func (*UnmarshalTypeError) Error

        func (e *UnmarshalTypeError) Error() string

        type Unmarshaler

        Unmarshaler is the interface implemented by types that can unmarshal a JSON description of themselves. The input can be assumed to be a valid encoding of a JSON value. UnmarshalJSON must copy the JSON data if it wishes to retain the data after returning.

        By convention, to approximate the behavior of Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.

        type Unmarshaler interface {
            UnmarshalJSON([]byte) error
        }

        type UnsupportedTypeError

        An UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.

        type UnsupportedTypeError struct {
            Type reflect.Type
        }
        

        func (*UnsupportedTypeError) Error

        func (e *UnsupportedTypeError) Error() string

        type UnsupportedValueError

        An UnsupportedValueError is returned by Marshal when attempting to encode an unsupported value.

        type UnsupportedValueError struct {
            Value reflect.Value
            Str   string
        }
        

        func (*UnsupportedValueError) Error

        func (e *UnsupportedValueError) Error() string
        pem - Go Documentation Server
        ...

        Package pem

        import "encoding/pem"
        Overview
        Index
        Examples

        Overview ▾

        Package pem implements the PEM data encoding, which originated in Privacy Enhanced Mail. The most common use of PEM encoding today is in TLS keys and certificates. See RFC 1421.

        func Encode

        func Encode(out io.Writer, b *Block) error

        Encode writes the PEM encoding of b to out.

        Example

        Code:

        block := &pem.Block{
            Type: "MESSAGE",
            Headers: map[string]string{
                "Animal": "Gopher",
            },
            Bytes: []byte("test"),
        }
        
        if err := pem.Encode(os.Stdout, block); err != nil {
            log.Fatal(err)
        }
        

        Output:

        -----BEGIN MESSAGE-----
        Animal: Gopher
        
        dGVzdA==
        -----END MESSAGE-----
        

        func EncodeToMemory

        func EncodeToMemory(b *Block) []byte

        EncodeToMemory returns the PEM encoding of b.

        If b has invalid headers and cannot be encoded, EncodeToMemory returns nil. If it is important to report details about this error case, use Encode instead.

        type Block

        A Block represents a PEM encoded structure.

        The encoded form is:

        -----BEGIN Type-----
        Headers
        base64-encoded Bytes
        -----END Type-----
        

        where [Block.Headers] is a possibly empty sequence of Key: Value lines.

        type Block struct {
            Type    string            // The type, taken from the preamble (i.e. "RSA PRIVATE KEY").
            Headers map[string]string // Optional headers.
            Bytes   []byte            // The decoded bytes of the contents. Typically a DER encoded ASN.1 structure.
        }
        

        func Decode

        func Decode(data []byte) (p *Block, rest []byte)

        Decode will find the next PEM formatted block (certificate, private key etc) in the input. It returns that block and the remainder of the input. If no PEM data is found, p is nil and the whole of the input is returned in rest.

        Example

        Code:

        var pubPEMData = []byte(`
        -----BEGIN PUBLIC KEY-----
        MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlRuRnThUjU8/prwYxbty
        WPT9pURI3lbsKMiB6Fn/VHOKE13p4D8xgOCADpdRagdT6n4etr9atzDKUSvpMtR3
        CP5noNc97WiNCggBjVWhs7szEe8ugyqF23XwpHQ6uV1LKH50m92MbOWfCtjU9p/x
        qhNpQQ1AZhqNy5Gevap5k8XzRmjSldNAFZMY7Yv3Gi+nyCwGwpVtBUwhuLzgNFK/
        yDtw2WcWmUU7NuC8Q6MWvPebxVtCfVp/iQU6q60yyt6aGOBkhAX0LpKAEhKidixY
        nP9PNVBvxgu3XZ4P36gZV6+ummKdBVnc3NqwBLu5+CcdRdusmHPHd5pHf4/38Z3/
        6qU2a/fPvWzceVTEgZ47QjFMTCTmCwNt29cvi7zZeQzjtwQgn4ipN9NibRH/Ax/q
        TbIzHfrJ1xa2RteWSdFjwtxi9C20HUkjXSeI4YlzQMH0fPX6KCE7aVePTOnB69I/
        a9/q96DiXZajwlpq3wFctrs1oXqBp5DVrCIj8hU2wNgB7LtQ1mCtsYz//heai0K9
        PhE4X6hiE0YmeAZjR0uHl8M/5aW9xCoJ72+12kKpWAa0SFRWLy6FejNYCYpkupVJ
        yecLk/4L1W0l6jQQZnWErXZYe0PNFcmwGXy1Rep83kfBRNKRy5tvocalLlwXLdUk
        AIU+2GKjyT3iMuzZxxFxPFMCAwEAAQ==
        -----END PUBLIC KEY-----
        and some more`)
        
        block, rest := pem.Decode(pubPEMData)
        if block == nil || block.Type != "PUBLIC KEY" {
            log.Fatal("failed to decode PEM block containing public key")
        }
        
        pub, err := x509.ParsePKIXPublicKey(block.Bytes)
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("Got a %T, with remaining data: %q", pub, rest)
        

        Output:

        Got a *rsa.PublicKey, with remaining data: "and some more"
        
        xml - Go Documentation Server
        ...

        Package xml

        import "encoding/xml"
        Overview
        Index
        Examples

        Overview ▾

        Package xml implements a simple XML 1.0 parser that understands XML name spaces.

        Example (CustomMarshalXML)

        Code:

        package xml_test
        
        import (
            "encoding/xml"
            "fmt"
            "log"
            "strings"
        )
        
        type Animal int
        
        const (
            Unknown Animal = iota
            Gopher
            Zebra
        )
        
        func (a *Animal) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
            var s string
            if err := d.DecodeElement(&s, &start); err != nil {
                return err
            }
            switch strings.ToLower(s) {
            default:
                *a = Unknown
            case "gopher":
                *a = Gopher
            case "zebra":
                *a = Zebra
            }
        
            return nil
        }
        
        func (a Animal) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
            var s string
            switch a {
            default:
                s = "unknown"
            case Gopher:
                s = "gopher"
            case Zebra:
                s = "zebra"
            }
            return e.EncodeElement(s, start)
        }
        
        func Example_customMarshalXML() {
            blob := `
            <animals>
                <animal>gopher</animal>
                <animal>armadillo</animal>
                <animal>zebra</animal>
                <animal>unknown</animal>
                <animal>gopher</animal>
                <animal>bee</animal>
                <animal>gopher</animal>
                <animal>zebra</animal>
            </animals>`
            var zoo struct {
                Animals []Animal `xml:"animal"`
            }
            if err := xml.Unmarshal([]byte(blob), &zoo); err != nil {
                log.Fatal(err)
            }
        
            census := make(map[Animal]int)
            for _, animal := range zoo.Animals {
                census[animal] += 1
            }
        
            fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras:  %d\n* Unknown: %d\n",
                census[Gopher], census[Zebra], census[Unknown])
        
            // Output:
            // Zoo Census:
            // * Gophers: 3
            // * Zebras:  2
            // * Unknown: 3
        }
        

        Example (TextMarshalXML)

        Code:

        package xml_test
        
        import (
            "encoding/xml"
            "fmt"
            "log"
            "strings"
        )
        
        type Size int
        
        const (
            Unrecognized Size = iota
            Small
            Large
        )
        
        func (s *Size) UnmarshalText(text []byte) error {
            switch strings.ToLower(string(text)) {
            default:
                *s = Unrecognized
            case "small":
                *s = Small
            case "large":
                *s = Large
            }
            return nil
        }
        
        func (s Size) MarshalText() ([]byte, error) {
            var name string
            switch s {
            default:
                name = "unrecognized"
            case Small:
                name = "small"
            case Large:
                name = "large"
            }
            return []byte(name), nil
        }
        
        func Example_textMarshalXML() {
            blob := `
            <sizes>
                <size>small</size>
                <size>regular</size>
                <size>large</size>
                <size>unrecognized</size>
                <size>small</size>
                <size>normal</size>
                <size>small</size>
                <size>large</size>
            </sizes>`
            var inventory struct {
                Sizes []Size `xml:"size"`
            }
            if err := xml.Unmarshal([]byte(blob), &inventory); err != nil {
                log.Fatal(err)
            }
        
            counts := make(map[Size]int)
            for _, size := range inventory.Sizes {
                counts[size] += 1
            }
        
            fmt.Printf("Inventory Counts:\n* Small:        %d\n* Large:        %d\n* Unrecognized: %d\n",
                counts[Small], counts[Large], counts[Unrecognized])
        
            // Output:
            // Inventory Counts:
            // * Small:        3
            // * Large:        2
            // * Unrecognized: 3
        }
        

        Index ▾

        Constants
        Variables
        func Escape(w io.Writer, s []byte)
        func EscapeText(w io.Writer, s []byte) error
        func Marshal(v any) ([]byte, error)
        func MarshalIndent(v any, prefix, indent string) ([]byte, error)
        func Unmarshal(data []byte, v any) error
        type Attr
        type CharData
            func (c CharData) Copy() CharData
        type Comment
            func (c Comment) Copy() Comment
        type Decoder
            func NewDecoder(r io.Reader) *Decoder
            func NewTokenDecoder(t TokenReader) *Decoder
            func (d *Decoder) Decode(v any) error
            func (d *Decoder) DecodeElement(v any, start *StartElement) error
            func (d *Decoder) InputOffset() int64
            func (d *Decoder) InputPos() (line, column int)
            func (d *Decoder) RawToken() (Token, error)
            func (d *Decoder) Skip() error
            func (d *Decoder) Token() (Token, error)
        type Directive
            func (d Directive) Copy() Directive
        type Encoder
            func NewEncoder(w io.Writer) *Encoder
            func (enc *Encoder) Close() error
            func (enc *Encoder) Encode(v any) error
            func (enc *Encoder) EncodeElement(v any, start StartElement) error
            func (enc *Encoder) EncodeToken(t Token) error
            func (enc *Encoder) Flush() error
            func (enc *Encoder) Indent(prefix, indent string)
        type EndElement
        type Marshaler
        type MarshalerAttr
        type Name
        type ProcInst
            func (p ProcInst) Copy() ProcInst
        type StartElement
            func (e StartElement) Copy() StartElement
            func (e StartElement) End() EndElement
        type SyntaxError
            func (e *SyntaxError) Error() string
        type TagPathError
            func (e *TagPathError) Error() string
        type Token
            func CopyToken(t Token) Token
        type TokenReader
        type UnmarshalError
            func (e UnmarshalError) Error() string
        type Unmarshaler
        type UnmarshalerAttr
        type UnsupportedTypeError
            func (e *UnsupportedTypeError) Error() string
        Bugs

        Package files

        marshal.go read.go typeinfo.go xml.go

        Constants

        const (
            // Header is a generic XML header suitable for use with the output of [Marshal].
            // This is not automatically added to any output of this package,
            // it is provided as a convenience.
            Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n"
        )

        Variables

        HTMLAutoClose is the set of HTML elements that should be considered to close automatically.

        See the [Decoder.Strict] and [Decoder.Entity] fields' documentation.

        var HTMLAutoClose []string = htmlAutoClose

        HTMLEntity is an entity map containing translations for the standard HTML entity characters.

        See the [Decoder.Strict] and [Decoder.Entity] fields' documentation.

        var HTMLEntity map[string]string = htmlEntity

        func Escape

        func Escape(w io.Writer, s []byte)

        Escape is like EscapeText but omits the error return value. It is provided for backwards compatibility with Go 1.0. Code targeting Go 1.1 or later should use EscapeText.

        func EscapeText

        func EscapeText(w io.Writer, s []byte) error

        EscapeText writes to w the properly escaped XML equivalent of the plain text data s.

        func Marshal

        func Marshal(v any) ([]byte, error)

        Marshal returns the XML encoding of v.

        Marshal handles an array or slice by marshaling each of the elements. Marshal handles a pointer by marshaling the value it points at or, if the pointer is nil, by writing nothing. Marshal handles an interface value by marshaling the value it contains or, if the interface value is nil, by writing nothing. Marshal handles all other data by writing one or more XML elements containing the data.

        The name for the XML elements is taken from, in order of preference:

        • the tag on the XMLName field, if the data is a struct
        • the value of the XMLName field of type Name
        • the tag of the struct field used to obtain the data
        • the name of the struct field used to obtain the data
        • the name of the marshaled type

        The XML element for a struct contains marshaled elements for each of the exported fields of the struct, with these exceptions:

        • the XMLName field, described above, is omitted.
        • a field with tag "-" is omitted.
        • a field with tag "name,attr" becomes an attribute with the given name in the XML element.
        • a field with tag ",attr" becomes an attribute with the field name in the XML element.
        • a field with tag ",chardata" is written as character data, not as an XML element.
        • a field with tag ",cdata" is written as character data wrapped in one or more <![CDATA[ ... ]]> tags, not as an XML element.
        • a field with tag ",innerxml" is written verbatim, not subject to the usual marshaling procedure.
        • a field with tag ",comment" is written as an XML comment, not subject to the usual marshaling procedure. It must not contain the "--" string within it.
        • a field with a tag including the "omitempty" option is omitted if the field value is empty. The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.
        • an anonymous struct field is handled as if the fields of its value were part of the outer struct.
        • a field implementing Marshaler is written by calling its MarshalXML method.
        • a field implementing encoding.TextMarshaler is written by encoding the result of its MarshalText method as text.

        If a field uses a tag "a>b>c", then the element c will be nested inside parent elements a and b. Fields that appear next to each other that name the same parent will be enclosed in one XML element.

        If the XML name for a struct field is defined by both the field tag and the struct's XMLName field, the names must match.

        See MarshalIndent for an example.

        Marshal will return an error if asked to marshal a channel, function, or map.

        func MarshalIndent

        func MarshalIndent(v any, prefix, indent string) ([]byte, error)

        MarshalIndent works like Marshal, but each XML element begins on a new indented line that starts with prefix and is followed by one or more copies of indent according to the nesting depth.

        Example

        Code:

        type Address struct {
            City, State string
        }
        type Person struct {
            XMLName   xml.Name `xml:"person"`
            Id        int      `xml:"id,attr"`
            FirstName string   `xml:"name>first"`
            LastName  string   `xml:"name>last"`
            Age       int      `xml:"age"`
            Height    float32  `xml:"height,omitempty"`
            Married   bool
            Address
            Comment string `xml:",comment"`
        }
        
        v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
        v.Comment = " Need more details. "
        v.Address = Address{"Hanga Roa", "Easter Island"}
        
        output, err := xml.MarshalIndent(v, "  ", "    ")
        if err != nil {
            fmt.Printf("error: %v\n", err)
        }
        
        os.Stdout.Write(output)
        

        Output:

          <person id="13">
              <name>
                  <first>John</first>
                  <last>Doe</last>
              </name>
              <age>42</age>
              <Married>false</Married>
              <City>Hanga Roa</City>
              <State>Easter Island</State>
              <!-- Need more details. -->
          </person>
        

        func Unmarshal

        func Unmarshal(data []byte, v any) error

        Unmarshal parses the XML-encoded data and stores the result in the value pointed to by v, which must be an arbitrary struct, slice, or string. Well-formed data that does not fit into v is discarded.

        Because Unmarshal uses the reflect package, it can only assign to exported (upper case) fields. Unmarshal uses a case-sensitive comparison to match XML element names to tag values and struct field names.

        Unmarshal maps an XML element to a struct using the following rules. In the rules, the tag of a field refers to the value associated with the key 'xml' in the struct field's tag (see the example above).

        • If the struct has a field of type []byte or string with tag ",innerxml", Unmarshal accumulates the raw XML nested inside the element in that field. The rest of the rules still apply.

        • If the struct has a field named XMLName of type Name, Unmarshal records the element name in that field.

        • If the XMLName field has an associated tag of the form "name" or "namespace-URL name", the XML element must have the given name (and, optionally, name space) or else Unmarshal returns an error.

        • If the XML element has an attribute whose name matches a struct field name with an associated tag containing ",attr" or the explicit name in a struct field tag of the form "name,attr", Unmarshal records the attribute value in that field.

        • If the XML element has an attribute not handled by the previous rule and the struct has a field with an associated tag containing ",any,attr", Unmarshal records the attribute value in the first such field.

        • If the XML element contains character data, that data is accumulated in the first struct field that has tag ",chardata". The struct field may have type []byte or string. If there is no such field, the character data is discarded.

        • If the XML element contains comments, they are accumulated in the first struct field that has tag ",comment". The struct field may have type []byte or string. If there is no such field, the comments are discarded.

        • If the XML element contains a sub-element whose name matches the prefix of a tag formatted as "a" or "a>b>c", unmarshal will descend into the XML structure looking for elements with the given names, and will map the innermost elements to that struct field. A tag starting with ">" is equivalent to one starting with the field name followed by ">".

        • If the XML element contains a sub-element whose name matches a struct field's XMLName tag and the struct field has no explicit name tag as per the previous rule, unmarshal maps the sub-element to that struct field.

        • If the XML element contains a sub-element whose name matches a field without any mode flags (",attr", ",chardata", etc), Unmarshal maps the sub-element to that struct field.

        • If the XML element contains a sub-element that hasn't matched any of the above rules and the struct has a field with tag ",any", unmarshal maps the sub-element to that struct field.

        • An anonymous struct field is handled as if the fields of its value were part of the outer struct.

        • A struct field with tag "-" is never unmarshaled into.

        If Unmarshal encounters a field type that implements the Unmarshaler interface, Unmarshal calls its UnmarshalXML method to produce the value from the XML element. Otherwise, if the value implements encoding.TextUnmarshaler, Unmarshal calls that value's UnmarshalText method.

        Unmarshal maps an XML element to a string or []byte by saving the concatenation of that element's character data in the string or []byte. The saved []byte is never nil.

        Unmarshal maps an attribute value to a string or []byte by saving the value in the string or slice.

        Unmarshal maps an attribute value to an Attr by saving the attribute, including its name, in the Attr.

        Unmarshal maps an XML element or attribute value to a slice by extending the length of the slice and mapping the element or attribute to the newly created value.

        Unmarshal maps an XML element or attribute value to a bool by setting it to the boolean value represented by the string. Whitespace is trimmed and ignored.

        Unmarshal maps an XML element or attribute value to an integer or floating-point field by setting the field to the result of interpreting the string value in decimal. There is no check for overflow. Whitespace is trimmed and ignored.

        Unmarshal maps an XML element to a Name by recording the element name.

        Unmarshal maps an XML element to a pointer by setting the pointer to a freshly allocated value and then mapping the element to that value.

        A missing element or empty attribute value will be unmarshaled as a zero value. If the field is a slice, a zero value will be appended to the field. Otherwise, the field will be set to its zero value.

        Example

        This example demonstrates unmarshaling an XML excerpt into a value with some preset fields. Note that the Phone field isn't modified and that the XML <Company> element is ignored. Also, the Groups field is assigned considering the element path provided in its tag.

        Code:

        type Email struct {
            Where string `xml:"where,attr"`
            Addr  string
        }
        type Address struct {
            City, State string
        }
        type Result struct {
            XMLName xml.Name `xml:"Person"`
            Name    string   `xml:"FullName"`
            Phone   string
            Email   []Email
            Groups  []string `xml:"Group>Value"`
            Address
        }
        v := Result{Name: "none", Phone: "none"}
        
        data := `
                <Person>
                    <FullName>Grace R. Emlin</FullName>
                    <Company>Example Inc.</Company>
                    <Email where="home">
                        <Addr>gre@example.com</Addr>
                    </Email>
                    <Email where='work'>
                        <Addr>gre@work.com</Addr>
                    </Email>
                    <Group>
                        <Value>Friends</Value>
                        <Value>Squash</Value>
                    </Group>
                    <City>Hanga Roa</City>
                    <State>Easter Island</State>
                </Person>
            `
        err := xml.Unmarshal([]byte(data), &v)
        if err != nil {
            fmt.Printf("error: %v", err)
            return
        }
        fmt.Printf("XMLName: %#v\n", v.XMLName)
        fmt.Printf("Name: %q\n", v.Name)
        fmt.Printf("Phone: %q\n", v.Phone)
        fmt.Printf("Email: %v\n", v.Email)
        fmt.Printf("Groups: %v\n", v.Groups)
        fmt.Printf("Address: %v\n", v.Address)
        

        Output:

        XMLName: xml.Name{Space:"", Local:"Person"}
        Name: "Grace R. Emlin"
        Phone: "none"
        Email: [{home gre@example.com} {work gre@work.com}]
        Groups: [Friends Squash]
        Address: {Hanga Roa Easter Island}
        

        type Attr

        An Attr represents an attribute in an XML element (Name=Value).

        type Attr struct {
            Name  Name
            Value string
        }
        

        type CharData

        A CharData represents XML character data (raw text), in which XML escape sequences have been replaced by the characters they represent.

        type CharData []byte

        func (CharData) Copy

        func (c CharData) Copy() CharData

        Copy creates a new copy of CharData.

        type Comment

        A Comment represents an XML comment of the form <!--comment-->. The bytes do not include the <!-- and --> comment markers.

        type Comment []byte

        func (Comment) Copy

        func (c Comment) Copy() Comment

        Copy creates a new copy of Comment.

        type Decoder

        A Decoder represents an XML parser reading a particular input stream. The parser assumes that its input is encoded in UTF-8.

        type Decoder struct {
            // Strict defaults to true, enforcing the requirements
            // of the XML specification.
            // If set to false, the parser allows input containing common
            // mistakes:
            //	* If an element is missing an end tag, the parser invents
            //	  end tags as necessary to keep the return values from Token
            //	  properly balanced.
            //	* In attribute values and character data, unknown or malformed
            //	  character entities (sequences beginning with &) are left alone.
            //
            // Setting:
            //
            //	d.Strict = false
            //	d.AutoClose = xml.HTMLAutoClose
            //	d.Entity = xml.HTMLEntity
            //
            // creates a parser that can handle typical HTML.
            //
            // Strict mode does not enforce the requirements of the XML name spaces TR.
            // In particular it does not reject name space tags using undefined prefixes.
            // Such tags are recorded with the unknown prefix as the name space URL.
            Strict bool
        
            // When Strict == false, AutoClose indicates a set of elements to
            // consider closed immediately after they are opened, regardless
            // of whether an end element is present.
            AutoClose []string
        
            // Entity can be used to map non-standard entity names to string replacements.
            // The parser behaves as if these standard mappings are present in the map,
            // regardless of the actual map content:
            //
            //	"lt": "<",
            //	"gt": ">",
            //	"amp": "&",
            //	"apos": "'",
            //	"quot": `"`,
            Entity map[string]string
        
            // CharsetReader, if non-nil, defines a function to generate
            // charset-conversion readers, converting from the provided
            // non-UTF-8 charset into UTF-8. If CharsetReader is nil or
            // returns an error, parsing stops with an error. One of the
            // CharsetReader's result values must be non-nil.
            CharsetReader func(charset string, input io.Reader) (io.Reader, error)
        
            // DefaultSpace sets the default name space used for unadorned tags,
            // as if the entire XML stream were wrapped in an element containing
            // the attribute xmlns="DefaultSpace".
            DefaultSpace string
            // contains filtered or unexported fields
        }
        

        func NewDecoder

        func NewDecoder(r io.Reader) *Decoder

        NewDecoder creates a new XML parser reading from r. If r does not implement io.ByteReader, NewDecoder will do its own buffering.

        func NewTokenDecoder

        func NewTokenDecoder(t TokenReader) *Decoder

        NewTokenDecoder creates a new XML parser using an underlying token stream.

        func (*Decoder) Decode

        func (d *Decoder) Decode(v any) error

        Decode works like Unmarshal, except it reads the decoder stream to find the start element.

        func (*Decoder) DecodeElement

        func (d *Decoder) DecodeElement(v any, start *StartElement) error

        DecodeElement works like Unmarshal except that it takes a pointer to the start XML element to decode into v. It is useful when a client reads some raw XML tokens itself but also wants to defer to Unmarshal for some elements.

        func (*Decoder) InputOffset

        func (d *Decoder) InputOffset() int64

        InputOffset returns the input stream byte offset of the current decoder position. The offset gives the location of the end of the most recently returned token and the beginning of the next token.

        func (*Decoder) InputPos

        func (d *Decoder) InputPos() (line, column int)

        InputPos returns the line of the current decoder position and the 1 based input position of the line. The position gives the location of the end of the most recently returned token.

        func (*Decoder) RawToken

        func (d *Decoder) RawToken() (Token, error)

        RawToken is like Decoder.Token but does not verify that start and end elements match and does not translate name space prefixes to their corresponding URLs.

        func (*Decoder) Skip

        func (d *Decoder) Skip() error

        Skip reads tokens until it has consumed the end element matching the most recent start element already consumed, skipping nested structures. It returns nil if it finds an end element matching the start element; otherwise it returns an error describing the problem.

        func (*Decoder) Token

        func (d *Decoder) Token() (Token, error)

        Token returns the next XML token in the input stream. At the end of the input stream, Token returns nil, io.EOF.

        Slices of bytes in the returned token data refer to the parser's internal buffer and remain valid only until the next call to Token. To acquire a copy of the bytes, call CopyToken or the token's Copy method.

        Token expands self-closing elements such as <br> into separate start and end elements returned by successive calls.

        Token guarantees that the StartElement and EndElement tokens it returns are properly nested and matched: if Token encounters an unexpected end element or EOF before all expected end elements, it will return an error.

        If [Decoder.CharsetReader] is called and returns an error, the error is wrapped and returned.

        Token implements XML name spaces as described by https://www.w3.org/TR/REC-xml-names/. Each of the Name structures contained in the Token has the Space set to the URL identifying its name space when known. If Token encounters an unrecognized name space prefix, it uses the prefix as the Space rather than report an error.

        type Directive

        A Directive represents an XML directive of the form <!text>. The bytes do not include the <! and > markers.

        type Directive []byte

        func (Directive) Copy

        func (d Directive) Copy() Directive

        Copy creates a new copy of Directive.

        type Encoder

        An Encoder writes XML data to an output stream.

        type Encoder struct {
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        type Address struct {
            City, State string
        }
        type Person struct {
            XMLName   xml.Name `xml:"person"`
            Id        int      `xml:"id,attr"`
            FirstName string   `xml:"name>first"`
            LastName  string   `xml:"name>last"`
            Age       int      `xml:"age"`
            Height    float32  `xml:"height,omitempty"`
            Married   bool
            Address
            Comment string `xml:",comment"`
        }
        
        v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
        v.Comment = " Need more details. "
        v.Address = Address{"Hanga Roa", "Easter Island"}
        
        enc := xml.NewEncoder(os.Stdout)
        enc.Indent("  ", "    ")
        if err := enc.Encode(v); err != nil {
            fmt.Printf("error: %v\n", err)
        }
        
        

        Output:

          <person id="13">
              <name>
                  <first>John</first>
                  <last>Doe</last>
              </name>
              <age>42</age>
              <Married>false</Married>
              <City>Hanga Roa</City>
              <State>Easter Island</State>
              <!-- Need more details. -->
          </person>
        

        func NewEncoder

        func NewEncoder(w io.Writer) *Encoder

        NewEncoder returns a new encoder that writes to w.

        func (*Encoder) Close

        func (enc *Encoder) Close() error

        Close the Encoder, indicating that no more data will be written. It flushes any buffered XML to the underlying writer and returns an error if the written XML is invalid (e.g. by containing unclosed elements).

        func (*Encoder) Encode

        func (enc *Encoder) Encode(v any) error

        Encode writes the XML encoding of v to the stream.

        See the documentation for Marshal for details about the conversion of Go values to XML.

        Encode calls Encoder.Flush before returning.

        func (*Encoder) EncodeElement

        func (enc *Encoder) EncodeElement(v any, start StartElement) error

        EncodeElement writes the XML encoding of v to the stream, using start as the outermost tag in the encoding.

        See the documentation for Marshal for details about the conversion of Go values to XML.

        EncodeElement calls Encoder.Flush before returning.

        func (*Encoder) EncodeToken

        func (enc *Encoder) EncodeToken(t Token) error

        EncodeToken writes the given XML token to the stream. It returns an error if StartElement and EndElement tokens are not properly matched.

        EncodeToken does not call Encoder.Flush, because usually it is part of a larger operation such as Encoder.Encode or Encoder.EncodeElement (or a custom Marshaler's MarshalXML invoked during those), and those will call Flush when finished. Callers that create an Encoder and then invoke EncodeToken directly, without using Encode or EncodeElement, need to call Flush when finished to ensure that the XML is written to the underlying writer.

        EncodeToken allows writing a ProcInst with Target set to "xml" only as the first token in the stream.

        func (*Encoder) Flush

        func (enc *Encoder) Flush() error

        Flush flushes any buffered XML to the underlying writer. See the Encoder.EncodeToken documentation for details about when it is necessary.

        func (*Encoder) Indent

        func (enc *Encoder) Indent(prefix, indent string)

        Indent sets the encoder to generate XML in which each element begins on a new indented line that starts with prefix and is followed by one or more copies of indent according to the nesting depth.

        type EndElement

        An EndElement represents an XML end element.

        type EndElement struct {
            Name Name
        }
        

        type Marshaler

        Marshaler is the interface implemented by objects that can marshal themselves into valid XML elements.

        MarshalXML encodes the receiver as zero or more XML elements. By convention, arrays or slices are typically encoded as a sequence of elements, one per entry. Using start as the element tag is not required, but doing so will enable Unmarshal to match the XML elements to the correct struct field. One common implementation strategy is to construct a separate value with a layout corresponding to the desired XML and then to encode it using e.EncodeElement. Another common strategy is to use repeated calls to e.EncodeToken to generate the XML output one token at a time. The sequence of encoded tokens must make up zero or more valid XML elements.

        type Marshaler interface {
            MarshalXML(e *Encoder, start StartElement) error
        }

        type MarshalerAttr

        MarshalerAttr is the interface implemented by objects that can marshal themselves into valid XML attributes.

        MarshalXMLAttr returns an XML attribute with the encoded value of the receiver. Using name as the attribute name is not required, but doing so will enable Unmarshal to match the attribute to the correct struct field. If MarshalXMLAttr returns the zero attribute Attr{}, no attribute will be generated in the output. MarshalXMLAttr is used only for struct fields with the "attr" option in the field tag.

        type MarshalerAttr interface {
            MarshalXMLAttr(name Name) (Attr, error)
        }

        type Name

        A Name represents an XML name (Local) annotated with a name space identifier (Space). In tokens returned by Decoder.Token, the Space identifier is given as a canonical URL, not the short prefix used in the document being parsed.

        type Name struct {
            Space, Local string
        }
        

        type ProcInst

        A ProcInst represents an XML processing instruction of the form <?target inst?>

        type ProcInst struct {
            Target string
            Inst   []byte
        }
        

        func (ProcInst) Copy

        func (p ProcInst) Copy() ProcInst

        Copy creates a new copy of ProcInst.

        type StartElement

        A StartElement represents an XML start element.

        type StartElement struct {
            Name Name
            Attr []Attr
        }
        

        func (StartElement) Copy

        func (e StartElement) Copy() StartElement

        Copy creates a new copy of StartElement.

        func (StartElement) End

        func (e StartElement) End() EndElement

        End returns the corresponding XML end element.

        type SyntaxError

        A SyntaxError represents a syntax error in the XML input stream.

        type SyntaxError struct {
            Msg  string
            Line int
        }
        

        func (*SyntaxError) Error

        func (e *SyntaxError) Error() string

        type TagPathError

        A TagPathError represents an error in the unmarshaling process caused by the use of field tags with conflicting paths.

        type TagPathError struct {
            Struct       reflect.Type
            Field1, Tag1 string
            Field2, Tag2 string
        }
        

        func (*TagPathError) Error

        func (e *TagPathError) Error() string

        type Token

        A Token is an interface holding one of the token types: StartElement, EndElement, CharData, Comment, ProcInst, or Directive.

        type Token any

        func CopyToken

        func CopyToken(t Token) Token

        CopyToken returns a copy of a Token.

        type TokenReader

        A TokenReader is anything that can decode a stream of XML tokens, including a Decoder.

        When Token encounters an error or end-of-file condition after successfully reading a token, it returns the token. It may return the (non-nil) error from the same call or return the error (and a nil token) from a subsequent call. An instance of this general case is that a TokenReader returning a non-nil token at the end of the token stream may return either io.EOF or a nil error. The next Read should return nil, io.EOF.

        Implementations of Token are discouraged from returning a nil token with a nil error. Callers should treat a return of nil, nil as indicating that nothing happened; in particular it does not indicate EOF.

        type TokenReader interface {
            Token() (Token, error)
        }

        type UnmarshalError

        An UnmarshalError represents an error in the unmarshaling process.

        type UnmarshalError string

        func (UnmarshalError) Error

        func (e UnmarshalError) Error() string

        type Unmarshaler

        Unmarshaler is the interface implemented by objects that can unmarshal an XML element description of themselves.

        UnmarshalXML decodes a single XML element beginning with the given start element. If it returns an error, the outer call to Unmarshal stops and returns that error. UnmarshalXML must consume exactly one XML element. One common implementation strategy is to unmarshal into a separate value with a layout matching the expected XML using d.DecodeElement, and then to copy the data from that value into the receiver. Another common strategy is to use d.Token to process the XML object one token at a time. UnmarshalXML may not use d.RawToken.

        type Unmarshaler interface {
            UnmarshalXML(d *Decoder, start StartElement) error
        }

        type UnmarshalerAttr

        UnmarshalerAttr is the interface implemented by objects that can unmarshal an XML attribute description of themselves.

        UnmarshalXMLAttr decodes a single XML attribute. If it returns an error, the outer call to Unmarshal stops and returns that error. UnmarshalXMLAttr is used only for struct fields with the "attr" option in the field tag.

        type UnmarshalerAttr interface {
            UnmarshalXMLAttr(attr Attr) error
        }

        type UnsupportedTypeError

        UnsupportedTypeError is returned when Marshal encounters a type that cannot be converted into XML.

        type UnsupportedTypeError struct {
            Type reflect.Type
        }
        

        func (*UnsupportedTypeError) Error

        func (e *UnsupportedTypeError) Error() string

        Bugs

        • Mapping between XML elements and data structures is inherently flawed: an XML element is an order-dependent collection of anonymous values, while a data structure is an order-independent collection of named values. See encoding/json for a textual representation more suitable to data structures.

        errors - Go Documentation Server
        ...

        Package errors

        import "errors"
        Overview
        Index
        Examples

        Overview ▾

        Package errors implements functions to manipulate errors.

        The New function creates errors whose only content is a text message.

        An error e wraps another error if e's type has one of the methods

        Unwrap() error
        Unwrap() []error
        

        If e.Unwrap() returns a non-nil error w or a slice containing w, then we say that e wraps w. A nil error returned from e.Unwrap() indicates that e does not wrap any error. It is invalid for an Unwrap method to return an []error containing a nil error value.

        An easy way to create wrapped errors is to call fmt.Errorf and apply the %w verb to the error argument:

        wrapsErr := fmt.Errorf("... %w ...", ..., err, ...)
        

        Successive unwrapping of an error creates a tree. The Is and As functions inspect an error's tree by examining first the error itself followed by the tree of each of its children in turn (pre-order, depth-first traversal).

        Is examines the tree of its first argument looking for an error that matches the second. It reports whether it finds a match. It should be used in preference to simple equality checks:

        if errors.Is(err, fs.ErrExist)
        

        is preferable to

        if err == fs.ErrExist
        

        because the former will succeed if err wraps io/fs.ErrExist.

        As examines the tree of its first argument looking for an error that can be assigned to its second argument, which must be a pointer. If it succeeds, it performs the assignment and returns true. Otherwise, it returns false. The form

        var perr *fs.PathError
        if errors.As(err, &perr) {
        	fmt.Println(perr.Path)
        }
        

        is preferable to

        if perr, ok := err.(*fs.PathError); ok {
        	fmt.Println(perr.Path)
        }
        

        because the former will succeed if err wraps an *io/fs.PathError.

        Example

        Code:

        if err := oops(); err != nil {
            fmt.Println(err)
        }
        

        Output:

        1989-03-15 22:30:00 +0000 UTC: the file system has gone away
        

        Variables

        ErrUnsupported indicates that a requested operation cannot be performed, because it is unsupported. For example, a call to os.Link when using a file system that does not support hard links.

        Functions and methods should not return this error but should instead return an error including appropriate context that satisfies

        errors.Is(err, errors.ErrUnsupported)
        

        either by directly wrapping ErrUnsupported or by implementing an Is method.

        Functions and methods should document the cases in which an error wrapping this will be returned.

        var ErrUnsupported = New("unsupported operation")

        func As

        func As(err error, target any) bool

        As finds the first error in err's tree that matches target, and if one is found, sets target to that error value and returns true. Otherwise, it returns false.

        The tree consists of err itself, followed by the errors obtained by repeatedly calling its Unwrap() error or Unwrap() []error method. When err wraps multiple errors, As examines err followed by a depth-first traversal of its children.

        An error matches target if the error's concrete value is assignable to the value pointed to by target, or if the error has a method As(interface{}) bool such that As(target) returns true. In the latter case, the As method is responsible for setting target.

        An error type might provide an As method so it can be treated as if it were a different error type.

        As panics if target is not a non-nil pointer to either a type that implements error, or to any interface type.

        Example

        Code:

        if _, err := os.Open("non-existing"); err != nil {
            var pathError *fs.PathError
            if errors.As(err, &pathError) {
                fmt.Println("Failed at path:", pathError.Path)
            } else {
                fmt.Println(err)
            }
        }
        
        

        Output:

        Failed at path: non-existing
        

        func Is

        func Is(err, target error) bool

        Is reports whether any error in err's tree matches target.

        The tree consists of err itself, followed by the errors obtained by repeatedly calling its Unwrap() error or Unwrap() []error method. When err wraps multiple errors, Is examines err followed by a depth-first traversal of its children.

        An error is considered to match a target if it is equal to that target or if it implements a method Is(error) bool such that Is(target) returns true.

        An error type might provide an Is method so it can be treated as equivalent to an existing error. For example, if MyError defines

        func (m MyError) Is(target error) bool { return target == fs.ErrExist }
        

        then Is(MyError{}, fs.ErrExist) returns true. See syscall.Errno.Is for an example in the standard library. An Is method should only shallowly compare err and the target and not call Unwrap on either.

        Example

        Code:

        if _, err := os.Open("non-existing"); err != nil {
            if errors.Is(err, fs.ErrNotExist) {
                fmt.Println("file does not exist")
            } else {
                fmt.Println(err)
            }
        }
        
        

        Output:

        file does not exist
        

        func Join

        func Join(errs ...error) error

        Join returns an error that wraps the given errors. Any nil error values are discarded. Join returns nil if every value in errs is nil. The error formats as the concatenation of the strings obtained by calling the Error method of each element of errs, with a newline between each string.

        A non-nil error returned by Join implements the Unwrap() []error method.

        Example

        Code:

        err1 := errors.New("err1")
        err2 := errors.New("err2")
        err := errors.Join(err1, err2)
        fmt.Println(err)
        if errors.Is(err, err1) {
            fmt.Println("err is err1")
        }
        if errors.Is(err, err2) {
            fmt.Println("err is err2")
        }
        

        Output:

        err1
        err2
        err is err1
        err is err2
        

        func New

        func New(text string) error

        New returns an error that formats as the given text. Each call to New returns a distinct error value even if the text is identical.

        Example

        Code:

        err := errors.New("emit macho dwarf: elf header corrupted")
        if err != nil {
            fmt.Print(err)
        }
        

        Output:

        emit macho dwarf: elf header corrupted
        

        Example (Errorf)

        The fmt package's Errorf function lets us use the package's formatting features to create descriptive error messages.

        Code:

        const name, id = "bimmler", 17
        err := fmt.Errorf("user %q (id %d) not found", name, id)
        if err != nil {
            fmt.Print(err)
        }
        

        Output:

        user "bimmler" (id 17) not found
        

        func Unwrap

        func Unwrap(err error) error

        Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.

        Unwrap only calls a method of the form "Unwrap() error". In particular Unwrap does not unwrap errors returned by Join.

        Example

        Code:

        err1 := errors.New("error1")
        err2 := fmt.Errorf("error2: [%w]", err1)
        fmt.Println(err2)
        fmt.Println(errors.Unwrap(err2))
        

        Output:

        error2: [error1]
        error1
        
        expvar - Go Documentation Server
        ...

        Package expvar

        import "expvar"
        Overview
        Index

        Overview ▾

        Package expvar provides a standardized interface to public variables, such as operation counters in servers. It exposes these variables via HTTP at /debug/vars in JSON format.

        Operations to set or modify these public variables are atomic.

        In addition to adding the HTTP handler, this package registers the following variables:

        cmdline   os.Args
        memstats  runtime.Memstats
        

        The package is sometimes only imported for the side effect of registering its HTTP handler and the above variables. To use it this way, link this package into your program:

        import _ "expvar"
        

        func Do

        func Do(f func(KeyValue))

        Do calls f for each exported variable. The global variable map is locked during the iteration, but existing entries may be concurrently updated.

        func Handler

        func Handler() http.Handler

        Handler returns the expvar HTTP Handler.

        This is only needed to install the handler in a non-standard location.

        func Publish

        func Publish(name string, v Var)

        Publish declares a named exported variable. This should be called from a package's init function when it creates its Vars. If the name is already registered then this will log.Panic.

        type Float

        Float is a 64-bit float variable that satisfies the Var interface.

        type Float struct {
            // contains filtered or unexported fields
        }
        

        func NewFloat

        func NewFloat(name string) *Float

        func (*Float) Add

        func (v *Float) Add(delta float64)

        Add adds delta to v.

        func (*Float) Set

        func (v *Float) Set(value float64)

        Set sets v to value.

        func (*Float) String

        func (v *Float) String() string

        func (*Float) Value

        func (v *Float) Value() float64

        type Func

        Func implements Var by calling the function and formatting the returned value using JSON.

        type Func func() any

        func (Func) String

        func (f Func) String() string

        func (Func) Value

        func (f Func) Value() any

        type Int

        Int is a 64-bit integer variable that satisfies the Var interface.

        type Int struct {
            // contains filtered or unexported fields
        }
        

        func NewInt

        func NewInt(name string) *Int

        func (*Int) Add

        func (v *Int) Add(delta int64)

        func (*Int) Set

        func (v *Int) Set(value int64)

        func (*Int) String

        func (v *Int) String() string

        func (*Int) Value

        func (v *Int) Value() int64

        type KeyValue

        KeyValue represents a single entry in a Map.

        type KeyValue struct {
            Key   string
            Value Var
        }
        

        type Map

        Map is a string-to-Var map variable that satisfies the Var interface.

        type Map struct {
            // contains filtered or unexported fields
        }
        

        func NewMap

        func NewMap(name string) *Map

        func (*Map) Add

        func (v *Map) Add(key string, delta int64)

        Add adds delta to the *Int value stored under the given map key.

        func (*Map) AddFloat

        func (v *Map) AddFloat(key string, delta float64)

        AddFloat adds delta to the *Float value stored under the given map key.

        func (*Map) Delete

        func (v *Map) Delete(key string)

        Delete deletes the given key from the map.

        func (*Map) Do

        func (v *Map) Do(f func(KeyValue))

        Do calls f for each entry in the map. The map is locked during the iteration, but existing entries may be concurrently updated.

        func (*Map) Get

        func (v *Map) Get(key string) Var

        func (*Map) Init

        func (v *Map) Init() *Map

        Init removes all keys from the map.

        func (*Map) Set

        func (v *Map) Set(key string, av Var)

        func (*Map) String

        func (v *Map) String() string

        type String

        String is a string variable, and satisfies the Var interface.

        type String struct {
            // contains filtered or unexported fields
        }
        

        func NewString

        func NewString(name string) *String

        func (*String) Set

        func (v *String) Set(value string)

        func (*String) String

        func (v *String) String() string

        String implements the Var interface. To get the unquoted string use String.Value.

        func (*String) Value

        func (v *String) Value() string

        type Var

        Var is an abstract type for all exported variables.

        type Var interface {
            // String returns a valid JSON value for the variable.
            // Types with String methods that do not return valid JSON
            // (such as time.Time) must not be used as a Var.
            String() string
        }

        func Get

        func Get(name string) Var

        Get retrieves a named exported variable. It returns nil if the name has not been registered.

        flag - Go Documentation Server
        ...

        Package flag

        import "flag"
        Overview
        Index
        Examples

        Overview ▾

        Package flag implements command-line flag parsing.

        Usage

        Define flags using flag.String, Bool, Int, etc.

        This declares an integer flag, -n, stored in the pointer nFlag, with type *int:

        import "flag"
        var nFlag = flag.Int("n", 1234, "help message for flag n")
        

        If you like, you can bind the flag to a variable using the Var() functions.

        var flagvar int
        func init() {
        	flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
        }
        

        Or you can create custom flags that satisfy the Value interface (with pointer receivers) and couple them to flag parsing by

        flag.Var(&flagVal, "name", "help message for flagname")
        

        For such flags, the default value is just the initial value of the variable.

        After all flags are defined, call

        flag.Parse()
        

        to parse the command line into the defined flags.

        Flags may then be used directly. If you're using the flags themselves, they are all pointers; if you bind to variables, they're values.

        fmt.Println("ip has value ", *ip)
        fmt.Println("flagvar has value ", flagvar)
        

        After parsing, the arguments following the flags are available as the slice flag.Args or individually as flag.Arg(i). The arguments are indexed from 0 through flag.NArg-1.

        Command line flag syntax

        The following forms are permitted:

        -flag
        --flag   // double dashes are also permitted
        -flag=x
        -flag x  // non-boolean flags only
        

        One or two dashes may be used; they are equivalent. The last form is not permitted for boolean flags because the meaning of the command

        cmd -x *
        

        where * is a Unix shell wildcard, will change if there is a file called 0, false, etc. You must use the -flag=false form to turn off a boolean flag.

        Flag parsing stops just before the first non-flag argument ("-" is a non-flag argument) or after the terminator "--".

        Integer flags accept 1234, 0664, 0x1234 and may be negative. Boolean flags may be:

        1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
        

        Duration flags accept any input valid for time.ParseDuration.

        The default set of command-line flags is controlled by top-level functions. The FlagSet type allows one to define independent sets of flags, such as to implement subcommands in a command-line interface. The methods of FlagSet are analogous to the top-level functions for the command-line flag set.

        Example

        Code:

        // These examples demonstrate more intricate uses of the flag package.
        package flag_test
        
        import (
            "errors"
            "flag"
            "fmt"
            "strings"
            "time"
        )
        
        // Example 1: A single string flag called "species" with default value "gopher".
        var species = flag.String("species", "gopher", "the species we are studying")
        
        // Example 2: Two flags sharing a variable, so we can have a shorthand.
        // The order of initialization is undefined, so make sure both use the
        // same default value. They must be set up with an init function.
        var gopherType string
        
        func init() {
            const (
                defaultGopher = "pocket"
                usage         = "the variety of gopher"
            )
            flag.StringVar(&gopherType, "gopher_type", defaultGopher, usage)
            flag.StringVar(&gopherType, "g", defaultGopher, usage+" (shorthand)")
        }
        
        // Example 3: A user-defined flag type, a slice of durations.
        type interval []time.Duration
        
        // String is the method to format the flag's value, part of the flag.Value interface.
        // The String method's output will be used in diagnostics.
        func (i *interval) String() string {
            return fmt.Sprint(*i)
        }
        
        // Set is the method to set the flag value, part of the flag.Value interface.
        // Set's argument is a string to be parsed to set the flag.
        // It's a comma-separated list, so we split it.
        func (i *interval) Set(value string) error {
            // If we wanted to allow the flag to be set multiple times,
            // accumulating values, we would delete this if statement.
            // That would permit usages such as
            //	-deltaT 10s -deltaT 15s
            // and other combinations.
            if len(*i) > 0 {
                return errors.New("interval flag already set")
            }
            for _, dt := range strings.Split(value, ",") {
                duration, err := time.ParseDuration(dt)
                if err != nil {
                    return err
                }
                *i = append(*i, duration)
            }
            return nil
        }
        
        // Define a flag to accumulate durations. Because it has a special type,
        // we need to use the Var function and therefore create the flag during
        // init.
        
        var intervalFlag interval
        
        func init() {
            // Tie the command-line flag to the intervalFlag variable and
            // set a usage message.
            flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events")
        }
        
        func Example() {
            // All the interesting pieces are with the variables declared above, but
            // to enable the flag package to see the flags defined there, one must
            // execute, typically at the start of main (not init!):
            //	flag.Parse()
            // We don't call it here because this code is a function called "Example"
            // that is part of the testing suite for the package, which has already
            // parsed the flags. When viewed at pkg.go.dev, however, the function is
            // renamed to "main" and it could be run as a standalone example.
        }
        

        Index ▾

        Variables
        func Arg(i int) string
        func Args() []string
        func Bool(name string, value bool, usage string) *bool
        func BoolFunc(name, usage string, fn func(string) error)
        func BoolVar(p *bool, name string, value bool, usage string)
        func Duration(name string, value time.Duration, usage string) *time.Duration
        func DurationVar(p *time.Duration, name string, value time.Duration, usage string)
        func Float64(name string, value float64, usage string) *float64
        func Float64Var(p *float64, name string, value float64, usage string)
        func Func(name, usage string, fn func(string) error)
        func Int(name string, value int, usage string) *int
        func Int64(name string, value int64, usage string) *int64
        func Int64Var(p *int64, name string, value int64, usage string)
        func IntVar(p *int, name string, value int, usage string)
        func NArg() int
        func NFlag() int
        func Parse()
        func Parsed() bool
        func PrintDefaults()
        func Set(name, value string) error
        func String(name string, value string, usage string) *string
        func StringVar(p *string, name string, value string, usage string)
        func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string)
        func Uint(name string, value uint, usage string) *uint
        func Uint64(name string, value uint64, usage string) *uint64
        func Uint64Var(p *uint64, name string, value uint64, usage string)
        func UintVar(p *uint, name string, value uint, usage string)
        func UnquoteUsage(flag *Flag) (name string, usage string)
        func Var(value Value, name string, usage string)
        func Visit(fn func(*Flag))
        func VisitAll(fn func(*Flag))
        type ErrorHandling
        type Flag
            func Lookup(name string) *Flag
        type FlagSet
            func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet
            func (f *FlagSet) Arg(i int) string
            func (f *FlagSet) Args() []string
            func (f *FlagSet) Bool(name string, value bool, usage string) *bool
            func (f *FlagSet) BoolFunc(name, usage string, fn func(string) error)
            func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string)
            func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration
            func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string)
            func (f *FlagSet) ErrorHandling() ErrorHandling
            func (f *FlagSet) Float64(name string, value float64, usage string) *float64
            func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string)
            func (f *FlagSet) Func(name, usage string, fn func(string) error)
            func (f *FlagSet) Init(name string, errorHandling ErrorHandling)
            func (f *FlagSet) Int(name string, value int, usage string) *int
            func (f *FlagSet) Int64(name string, value int64, usage string) *int64
            func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string)
            func (f *FlagSet) IntVar(p *int, name string, value int, usage string)
            func (f *FlagSet) Lookup(name string) *Flag
            func (f *FlagSet) NArg() int
            func (f *FlagSet) NFlag() int
            func (f *FlagSet) Name() string
            func (f *FlagSet) Output() io.Writer
            func (f *FlagSet) Parse(arguments []string) error
            func (f *FlagSet) Parsed() bool
            func (f *FlagSet) PrintDefaults()
            func (f *FlagSet) Set(name, value string) error
            func (f *FlagSet) SetOutput(output io.Writer)
            func (f *FlagSet) String(name string, value string, usage string) *string
            func (f *FlagSet) StringVar(p *string, name string, value string, usage string)
            func (f *FlagSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string)
            func (f *FlagSet) Uint(name string, value uint, usage string) *uint
            func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64
            func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string)
            func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string)
            func (f *FlagSet) Var(value Value, name string, usage string)
            func (f *FlagSet) Visit(fn func(*Flag))
            func (f *FlagSet) VisitAll(fn func(*Flag))
        type Getter
        type Value

        Examples

        Package
        BoolFunc
        Func
        TextVar
        Value

        Package files

        flag.go

        Variables

        CommandLine is the default set of command-line flags, parsed from os.Args. The top-level functions such as BoolVar, Arg, and so on are wrappers for the methods of CommandLine.

        var CommandLine = NewFlagSet(os.Args[0], ExitOnError)

        ErrHelp is the error returned if the -help or -h flag is invoked but no such flag is defined.

        var ErrHelp = errors.New("flag: help requested")

        Usage prints a usage message documenting all defined command-line flags to CommandLine's output, which by default is os.Stderr. It is called when an error occurs while parsing flags. The function is a variable that may be changed to point to a custom function. By default it prints a simple header and calls PrintDefaults; for details about the format of the output and how to control it, see the documentation for PrintDefaults. Custom usage functions may choose to exit the program; by default exiting happens anyway as the command line's error handling strategy is set to ExitOnError.

        var Usage = func() {
            fmt.Fprintf(CommandLine.Output(), "Usage of %s:\n", os.Args[0])
            PrintDefaults()
        }

        func Arg

        func Arg(i int) string

        Arg returns the i'th command-line argument. Arg(0) is the first remaining argument after flags have been processed. Arg returns an empty string if the requested element does not exist.

        func Args

        func Args() []string

        Args returns the non-flag command-line arguments.

        func Bool

        func Bool(name string, value bool, usage string) *bool

        Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.

        func BoolFunc

        func BoolFunc(name, usage string, fn func(string) error)

        BoolFunc defines a flag with the specified name and usage string without requiring values. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.

        Example

        Code:

        fs := flag.NewFlagSet("ExampleBoolFunc", flag.ContinueOnError)
        fs.SetOutput(os.Stdout)
        
        fs.BoolFunc("log", "logs a dummy message", func(s string) error {
            fmt.Println("dummy message:", s)
            return nil
        })
        fs.Parse([]string{"-log"})
        fs.Parse([]string{"-log=0"})
        
        

        Output:

        dummy message: true
        dummy message: 0
        

        func BoolVar

        func BoolVar(p *bool, name string, value bool, usage string)

        BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.

        func Duration

        func Duration(name string, value time.Duration, usage string) *time.Duration

        Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag. The flag accepts a value acceptable to time.ParseDuration.

        func DurationVar

        func DurationVar(p *time.Duration, name string, value time.Duration, usage string)

        DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag. The flag accepts a value acceptable to time.ParseDuration.

        func Float64

        func Float64(name string, value float64, usage string) *float64

        Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.

        func Float64Var

        func Float64Var(p *float64, name string, value float64, usage string)

        Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.

        func Func

        func Func(name, usage string, fn func(string) error)

        Func defines a flag with the specified name and usage string. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.

        Example

        Code:

        fs := flag.NewFlagSet("ExampleFunc", flag.ContinueOnError)
        fs.SetOutput(os.Stdout)
        var ip net.IP
        fs.Func("ip", "`IP address` to parse", func(s string) error {
            ip = net.ParseIP(s)
            if ip == nil {
                return errors.New("could not parse IP")
            }
            return nil
        })
        fs.Parse([]string{"-ip", "127.0.0.1"})
        fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback())
        
        // 256 is not a valid IPv4 component
        fs.Parse([]string{"-ip", "256.0.0.1"})
        fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback())
        
        

        Output:

        {ip: 127.0.0.1, loopback: true}
        
        invalid value "256.0.0.1" for flag -ip: could not parse IP
        Usage of ExampleFunc:
          -ip IP address
            	IP address to parse
        {ip: <nil>, loopback: false}
        

        func Int

        func Int(name string, value int, usage string) *int

        Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.

        func Int64

        func Int64(name string, value int64, usage string) *int64

        Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.

        func Int64Var

        func Int64Var(p *int64, name string, value int64, usage string)

        Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.

        func IntVar

        func IntVar(p *int, name string, value int, usage string)

        IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.

        func NArg

        func NArg() int

        NArg is the number of arguments remaining after flags have been processed.

        func NFlag

        func NFlag() int

        NFlag returns the number of command-line flags that have been set.

        func Parse

        func Parse()

        Parse parses the command-line flags from os.Args[1:]. Must be called after all flags are defined and before flags are accessed by the program.

        func Parsed

        func Parsed() bool

        Parsed reports whether the command-line flags have been parsed.

        func PrintDefaults

        func PrintDefaults()

        PrintDefaults prints, to standard error unless configured otherwise, a usage message showing the default settings of all defined command-line flags. For an integer valued flag x, the default output has the form

        -x int
        	usage-message-for-x (default 7)
        

        The usage message will appear on a separate line for anything but a bool flag with a one-byte name. For bool flags, the type is omitted and if the flag name is one byte the usage message appears on the same line. The parenthetical default is omitted if the default is the zero value for the type. The listed type, here int, can be changed by placing a back-quoted name in the flag's usage string; the first such item in the message is taken to be a parameter name to show in the message and the back quotes are stripped from the message when displayed. For instance, given

        flag.String("I", "", "search `directory` for include files")
        

        the output will be

        -I directory
        	search directory for include files.
        

        To change the destination for flag messages, call CommandLine.SetOutput.

        func Set

        func Set(name, value string) error

        Set sets the value of the named command-line flag.

        func String

        func String(name string, value string, usage string) *string

        String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.

        func StringVar

        func StringVar(p *string, name string, value string, usage string)

        StringVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.

        func TextVar

        func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string)

        TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p.

        Example

        Code:

        fs := flag.NewFlagSet("ExampleTextVar", flag.ContinueOnError)
        fs.SetOutput(os.Stdout)
        var ip net.IP
        fs.TextVar(&ip, "ip", net.IPv4(192, 168, 0, 100), "`IP address` to parse")
        fs.Parse([]string{"-ip", "127.0.0.1"})
        fmt.Printf("{ip: %v}\n\n", ip)
        
        // 256 is not a valid IPv4 component
        ip = nil
        fs.Parse([]string{"-ip", "256.0.0.1"})
        fmt.Printf("{ip: %v}\n\n", ip)
        
        

        Output:

        {ip: 127.0.0.1}
        
        invalid value "256.0.0.1" for flag -ip: invalid IP address: 256.0.0.1
        Usage of ExampleTextVar:
          -ip IP address
            	IP address to parse (default 192.168.0.100)
        {ip: <nil>}
        

        func Uint

        func Uint(name string, value uint, usage string) *uint

        Uint defines a uint flag with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the flag.

        func Uint64

        func Uint64(name string, value uint64, usage string) *uint64

        Uint64 defines a uint64 flag with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the flag.

        func Uint64Var

        func Uint64Var(p *uint64, name string, value uint64, usage string)

        Uint64Var defines a uint64 flag with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the flag.

        func UintVar

        func UintVar(p *uint, name string, value uint, usage string)

        UintVar defines a uint flag with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the flag.

        func UnquoteUsage

        func UnquoteUsage(flag *Flag) (name string, usage string)

        UnquoteUsage extracts a back-quoted name from the usage string for a flag and returns it and the un-quoted usage. Given "a `name` to show" it returns ("name", "a name to show"). If there are no back quotes, the name is an educated guess of the type of the flag's value, or the empty string if the flag is boolean.

        func Var

        func Var(value Value, name string, usage string)

        Var defines a flag with the specified name and usage string. The type and value of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.

        func Visit

        func Visit(fn func(*Flag))

        Visit visits the command-line flags in lexicographical order, calling fn for each. It visits only those flags that have been set.

        func VisitAll

        func VisitAll(fn func(*Flag))

        VisitAll visits the command-line flags in lexicographical order, calling fn for each. It visits all flags, even those not set.

        type ErrorHandling

        ErrorHandling defines how FlagSet.Parse behaves if the parse fails.

        type ErrorHandling int

        These constants cause FlagSet.Parse to behave as described if the parse fails.

        const (
            ContinueOnError ErrorHandling = iota // Return a descriptive error.
            ExitOnError                          // Call os.Exit(2) or for -h/-help Exit(0).
            PanicOnError                         // Call panic with a descriptive error.
        )

        type Flag

        A Flag represents the state of a flag.

        type Flag struct {
            Name     string // name as it appears on command line
            Usage    string // help message
            Value    Value  // value as set
            DefValue string // default value (as text); for usage message
        }
        

        func Lookup

        func Lookup(name string) *Flag

        Lookup returns the Flag structure of the named command-line flag, returning nil if none exists.

        type FlagSet

        A FlagSet represents a set of defined flags. The zero value of a FlagSet has no name and has ContinueOnError error handling.

        Flag names must be unique within a FlagSet. An attempt to define a flag whose name is already in use will cause a panic.

        type FlagSet struct {
            // Usage is the function called when an error occurs while parsing flags.
            // The field is a function (not a method) that may be changed to point to
            // a custom error handler. What happens after Usage is called depends
            // on the ErrorHandling setting; for the command line, this defaults
            // to ExitOnError, which exits the program after calling Usage.
            Usage func()
            // contains filtered or unexported fields
        }
        

        func NewFlagSet

        func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet

        NewFlagSet returns a new, empty flag set with the specified name and error handling property. If the name is not empty, it will be printed in the default usage message and in error messages.

        func (*FlagSet) Arg

        func (f *FlagSet) Arg(i int) string

        Arg returns the i'th argument. Arg(0) is the first remaining argument after flags have been processed. Arg returns an empty string if the requested element does not exist.

        func (*FlagSet) Args

        func (f *FlagSet) Args() []string

        Args returns the non-flag arguments.

        func (*FlagSet) Bool

        func (f *FlagSet) Bool(name string, value bool, usage string) *bool

        Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.

        func (*FlagSet) BoolFunc

        func (f *FlagSet) BoolFunc(name, usage string, fn func(string) error)

        BoolFunc defines a flag with the specified name and usage string without requiring values. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.

        func (*FlagSet) BoolVar

        func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string)

        BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.

        func (*FlagSet) Duration

        func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration

        Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag. The flag accepts a value acceptable to time.ParseDuration.

        func (*FlagSet) DurationVar

        func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string)

        DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag. The flag accepts a value acceptable to time.ParseDuration.

        func (*FlagSet) ErrorHandling

        func (f *FlagSet) ErrorHandling() ErrorHandling

        ErrorHandling returns the error handling behavior of the flag set.

        func (*FlagSet) Float64

        func (f *FlagSet) Float64(name string, value float64, usage string) *float64

        Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.

        func (*FlagSet) Float64Var

        func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string)

        Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.

        func (*FlagSet) Func

        func (f *FlagSet) Func(name, usage string, fn func(string) error)

        Func defines a flag with the specified name and usage string. Each time the flag is seen, fn is called with the value of the flag. If fn returns a non-nil error, it will be treated as a flag value parsing error.

        func (*FlagSet) Init

        func (f *FlagSet) Init(name string, errorHandling ErrorHandling)

        Init sets the name and error handling property for a flag set. By default, the zero FlagSet uses an empty name and the ContinueOnError error handling policy.

        func (*FlagSet) Int

        func (f *FlagSet) Int(name string, value int, usage string) *int

        Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.

        func (*FlagSet) Int64

        func (f *FlagSet) Int64(name string, value int64, usage string) *int64

        Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.

        func (*FlagSet) Int64Var

        func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string)

        Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.

        func (*FlagSet) IntVar

        func (f *FlagSet) IntVar(p *int, name string, value int, usage string)

        IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.

        func (*FlagSet) Lookup

        func (f *FlagSet) Lookup(name string) *Flag

        Lookup returns the Flag structure of the named flag, returning nil if none exists.

        func (*FlagSet) NArg

        func (f *FlagSet) NArg() int

        NArg is the number of arguments remaining after flags have been processed.

        func (*FlagSet) NFlag

        func (f *FlagSet) NFlag() int

        NFlag returns the number of flags that have been set.

        func (*FlagSet) Name

        func (f *FlagSet) Name() string

        Name returns the name of the flag set.

        func (*FlagSet) Output

        func (f *FlagSet) Output() io.Writer

        Output returns the destination for usage and error messages. os.Stderr is returned if output was not set or was set to nil.

        func (*FlagSet) Parse

        func (f *FlagSet) Parse(arguments []string) error

        Parse parses flag definitions from the argument list, which should not include the command name. Must be called after all flags in the FlagSet are defined and before flags are accessed by the program. The return value will be ErrHelp if -help or -h were set but not defined.

        func (*FlagSet) Parsed

        func (f *FlagSet) Parsed() bool

        Parsed reports whether f.Parse has been called.

        func (*FlagSet) PrintDefaults

        func (f *FlagSet) PrintDefaults()

        PrintDefaults prints, to standard error unless configured otherwise, the default values of all defined command-line flags in the set. See the documentation for the global function PrintDefaults for more information.

        func (*FlagSet) Set

        func (f *FlagSet) Set(name, value string) error

        Set sets the value of the named flag.

        func (*FlagSet) SetOutput

        func (f *FlagSet) SetOutput(output io.Writer)

        SetOutput sets the destination for usage and error messages. If output is nil, os.Stderr is used.

        func (*FlagSet) String

        func (f *FlagSet) String(name string, value string, usage string) *string

        String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.

        func (*FlagSet) StringVar

        func (f *FlagSet) StringVar(p *string, name string, value string, usage string)

        StringVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.

        func (*FlagSet) TextVar

        func (f *FlagSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string)

        TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p.

        func (*FlagSet) Uint

        func (f *FlagSet) Uint(name string, value uint, usage string) *uint

        Uint defines a uint flag with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the flag.

        func (*FlagSet) Uint64

        func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64

        Uint64 defines a uint64 flag with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the flag.

        func (*FlagSet) Uint64Var

        func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string)

        Uint64Var defines a uint64 flag with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the flag.

        func (*FlagSet) UintVar

        func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string)

        UintVar defines a uint flag with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the flag.

        func (*FlagSet) Var

        func (f *FlagSet) Var(value Value, name string, usage string)

        Var defines a flag with the specified name and usage string. The type and value of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.

        func (*FlagSet) Visit

        func (f *FlagSet) Visit(fn func(*Flag))

        Visit visits the flags in lexicographical order, calling fn for each. It visits only those flags that have been set.

        func (*FlagSet) VisitAll

        func (f *FlagSet) VisitAll(fn func(*Flag))

        VisitAll visits the flags in lexicographical order, calling fn for each. It visits all flags, even those not set.

        type Getter

        Getter is an interface that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface, except the type used by Func.

        type Getter interface {
            Value
            Get() any
        }

        type Value

        Value is the interface to the dynamic value stored in a flag. (The default value is represented as a string.)

        If a Value has an IsBoolFlag() bool method returning true, the command-line parser makes -name equivalent to -name=true rather than using the next command-line argument.

        Set is called once, in command line order, for each flag present. The flag package may call the String method with a zero-valued receiver, such as a nil pointer.

        type Value interface {
            String() string
            Set(string) error
        }

        Example

        Code:

        package flag_test
        
        import (
            "flag"
            "fmt"
            "net/url"
        )
        
        type URLValue struct {
            URL *url.URL
        }
        
        func (v URLValue) String() string {
            if v.URL != nil {
                return v.URL.String()
            }
            return ""
        }
        
        func (v URLValue) Set(s string) error {
            if u, err := url.Parse(s); err != nil {
                return err
            } else {
                *v.URL = *u
            }
            return nil
        }
        
        var u = &url.URL{}
        
        func ExampleValue() {
            fs := flag.NewFlagSet("ExampleValue", flag.ExitOnError)
            fs.Var(&URLValue{u}, "url", "URL to parse")
        
            fs.Parse([]string{"-url", "https://golang.org/pkg/flag/"})
            fmt.Printf(`{scheme: %q, host: %q, path: %q}`, u.Scheme, u.Host, u.Path)
        
            // Output:
            // {scheme: "https", host: "golang.org", path: "/pkg/flag/"}
        }
        
        fmt - Go Documentation Server
        ...

        Package fmt

        import "fmt"
        Overview
        Index
        Examples

        Overview ▾

        Package fmt implements formatted I/O with functions analogous to C's printf and scanf. The format 'verbs' are derived from C's but are simpler.

        Printing

        The verbs:

        General:

        %v	the value in a default format
        	when printing structs, the plus flag (%+v) adds field names
        %#v	a Go-syntax representation of the value
        %T	a Go-syntax representation of the type of the value
        %%	a literal percent sign; consumes no value
        

        Boolean:

        %t	the word true or false
        

        Integer:

        %b	base 2
        %c	the character represented by the corresponding Unicode code point
        %d	base 10
        %o	base 8
        %O	base 8 with 0o prefix
        %q	a single-quoted character literal safely escaped with Go syntax.
        %x	base 16, with lower-case letters for a-f
        %X	base 16, with upper-case letters for A-F
        %U	Unicode format: U+1234; same as "U+%04X"
        

        Floating-point and complex constituents:

        %b	decimalless scientific notation with exponent a power of two,
        	in the manner of strconv.FormatFloat with the 'b' format,
        	e.g. -123456p-78
        %e	scientific notation, e.g. -1.234456e+78
        %E	scientific notation, e.g. -1.234456E+78
        %f	decimal point but no exponent, e.g. 123.456
        %F	synonym for %f
        %g	%e for large exponents, %f otherwise. Precision is discussed below.
        %G	%E for large exponents, %F otherwise
        %x	hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20
        %X	upper-case hexadecimal notation, e.g. -0X1.23ABCP+20
        

        String and slice of bytes (treated equivalently with these verbs):

        %s	the uninterpreted bytes of the string or slice
        %q	a double-quoted string safely escaped with Go syntax
        %x	base 16, lower-case, two characters per byte
        %X	base 16, upper-case, two characters per byte
        

        Slice:

        %p	address of 0th element in base 16 notation, with leading 0x
        

        Pointer:

        %p	base 16 notation, with leading 0x
        The %b, %d, %o, %x and %X verbs also work with pointers,
        formatting the value exactly as if it were an integer.
        

        The default format for %v is:

        bool:                    %t
        int, int8 etc.:          %d
        uint, uint8 etc.:        %d, %#x if printed with %#v
        float32, complex64, etc: %g
        string:                  %s
        chan:                    %p
        pointer:                 %p
        

        For compound objects, the elements are printed using these rules, recursively, laid out like this:

        struct:             {field0 field1 ...}
        array, slice:       [elem0 elem1 ...]
        maps:               map[key1:value1 key2:value2 ...]
        pointer to above:   &{}, &[], &map[]
        

        Width is specified by an optional decimal number immediately preceding the verb. If absent, the width is whatever is necessary to represent the value. Precision is specified after the (optional) width by a period followed by a decimal number. If no period is present, a default precision is used. A period with no following number specifies a precision of zero. Examples:

        %f     default width, default precision
        %9f    width 9, default precision
        %.2f   default width, precision 2
        %9.2f  width 9, precision 2
        %9.f   width 9, precision 0
        

        Width and precision are measured in units of Unicode code points, that is, runes. (This differs from C's printf where the units are always measured in bytes.) Either or both of the flags may be replaced with the character '*', causing their values to be obtained from the next operand (preceding the one to format), which must be of type int.

        For most values, width is the minimum number of runes to output, padding the formatted form with spaces if necessary.

        For strings, byte slices and byte arrays, however, precision limits the length of the input to be formatted (not the size of the output), truncating if necessary. Normally it is measured in runes, but for these types when formatted with the %x or %X format it is measured in bytes.

        For floating-point values, width sets the minimum width of the field and precision sets the number of places after the decimal, if appropriate, except that for %g/%G precision sets the maximum number of significant digits (trailing zeros are removed). For example, given 12.345 the format %6.3f prints 12.345 while %.3g prints 12.3. The default precision for %e, %f and %#g is 6; for %g it is the smallest number of digits necessary to identify the value uniquely.

        For complex numbers, the width and precision apply to the two components independently and the result is parenthesized, so %f applied to 1.2+3.4i produces (1.200000+3.400000i).

        When formatting a single integer code point or a rune string (type []rune) with %q, invalid Unicode code points are changed to the Unicode replacement character, U+FFFD, as in strconv.QuoteRune.

        Other flags:

        '+'	always print a sign for numeric values;
        	guarantee ASCII-only output for %q (%+q)
        '-'	pad with spaces on the right rather than the left (left-justify the field)
        '#'	alternate format: add leading 0b for binary (%#b), 0 for octal (%#o),
        	0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p);
        	for %q, print a raw (backquoted) string if strconv.CanBackquote
        	returns true;
        	always print a decimal point for %e, %E, %f, %F, %g and %G;
        	do not remove trailing zeros for %g and %G;
        	write e.g. U+0078 'x' if the character is printable for %U (%#U).
        ' '	(space) leave a space for elided sign in numbers (% d);
        	put spaces between bytes printing strings or slices in hex (% x, % X)
        '0'	pad with leading zeros rather than spaces;
        	for numbers, this moves the padding after the sign;
        	ignored for strings, byte slices and byte arrays
        

        Flags are ignored by verbs that do not expect them. For example there is no alternate decimal format, so %#d and %d behave identically.

        For each Printf-like function, there is also a Print function that takes no format and is equivalent to saying %v for every operand. Another variant Println inserts blanks between operands and appends a newline.

        Regardless of the verb, if an operand is an interface value, the internal concrete value is used, not the interface itself. Thus:

        var i interface{} = 23
        fmt.Printf("%v\n", i)
        

        will print 23.

        Except when printed using the verbs %T and %p, special formatting considerations apply for operands that implement certain interfaces. In order of application:

        1. If the operand is a reflect.Value, the operand is replaced by the concrete value that it holds, and printing continues with the next rule.

        2. If an operand implements the Formatter interface, it will be invoked. In this case the interpretation of verbs and flags is controlled by that implementation.

        3. If the %v verb is used with the # flag (%#v) and the operand implements the GoStringer interface, that will be invoked.

        If the format (which is implicitly %v for Println etc.) is valid for a string (%s %q %x %X), or is %v but not %#v, the following two rules apply:

        4. If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

        5. If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

        For compound operands such as slices and structs, the format applies to the elements of each operand, recursively, not to the operand as a whole. Thus %q will quote each element of a slice of strings, and %6.2f will control formatting for each element of a floating-point array.

        However, when printing a byte slice with a string-like verb (%s %q %x %X), it is treated identically to a string, as a single item.

        To avoid recursion in cases such as

        type X string
        func (x X) String() string { return Sprintf("<%s>", x) }
        

        convert the value before recurring:

        func (x X) String() string { return Sprintf("<%s>", string(x)) }
        

        Infinite recursion can also be triggered by self-referential data structures, such as a slice that contains itself as an element, if that type has a String method. Such pathologies are rare, however, and the package does not protect against them.

        When printing a struct, fmt cannot and therefore does not invoke formatting methods such as Error or String on unexported fields.

        Explicit argument indexes

        In Printf, Sprintf, and Fprintf, the default behavior is for each formatting verb to format successive arguments passed in the call. However, the notation [n] immediately before the verb indicates that the nth one-indexed argument is to be formatted instead. The same notation before a '*' for a width or precision selects the argument index holding the value. After processing a bracketed expression [n], subsequent verbs will use arguments n+1, n+2, etc. unless otherwise directed.

        For example,

        fmt.Sprintf("%[2]d %[1]d\n", 11, 22)
        

        will yield "22 11", while

        fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6)
        

        equivalent to

        fmt.Sprintf("%6.2f", 12.0)
        

        will yield " 12.00". Because an explicit index affects subsequent verbs, this notation can be used to print the same values multiple times by resetting the index for the first argument to be repeated:

        fmt.Sprintf("%d %d %#[1]x %#x", 16, 17)
        

        will yield "16 17 0x10 0x11".

        Format errors

        If an invalid argument is given for a verb, such as providing a string to %d, the generated string will contain a description of the problem, as in these examples:

        Wrong type or unknown verb: %!verb(type=value)
        	Printf("%d", "hi"):        %!d(string=hi)
        Too many arguments: %!(EXTRA type=value)
        	Printf("hi", "guys"):      hi%!(EXTRA string=guys)
        Too few arguments: %!verb(MISSING)
        	Printf("hi%d"):            hi%!d(MISSING)
        Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
        	Printf("%*s", 4.5, "hi"):  %!(BADWIDTH)hi
        	Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
        Invalid or invalid use of argument index: %!(BADINDEX)
        	Printf("%*[2]d", 7):       %!d(BADINDEX)
        	Printf("%.[2]d", 7):       %!d(BADINDEX)
        

        All errors begin with the string "%!" followed sometimes by a single character (the verb) and end with a parenthesized description.

        If an Error or String method triggers a panic when called by a print routine, the fmt package reformats the error message from the panic, decorating it with an indication that it came through the fmt package. For example, if a String method calls panic("bad"), the resulting formatted message will look like

        %!s(PANIC=bad)
        

        The %!s just shows the print verb in use when the failure occurred. If the panic is caused by a nil receiver to an Error or String method, however, the output is the undecorated string, "<nil>".

        Scanning

        An analogous set of functions scans formatted text to yield values. Scan, Scanf and Scanln read from os.Stdin; Fscan, Fscanf and Fscanln read from a specified io.Reader; Sscan, Sscanf and Sscanln read from an argument string.

        Scan, Fscan, Sscan treat newlines in the input as spaces.

        Scanln, Fscanln and Sscanln stop scanning at a newline and require that the items be followed by a newline or EOF.

        Scanf, Fscanf, and Sscanf parse the arguments according to a format string, analogous to that of Printf. In the text that follows, 'space' means any Unicode whitespace character except newline.

        In the format string, a verb introduced by the % character consumes and parses input; these verbs are described in more detail below. A character other than %, space, or newline in the format consumes exactly that input character, which must be present. A newline with zero or more spaces before it in the format string consumes zero or more spaces in the input followed by a single newline or the end of the input. A space following a newline in the format string consumes zero or more spaces in the input. Otherwise, any run of one or more spaces in the format string consumes as many spaces as possible in the input. Unless the run of spaces in the format string appears adjacent to a newline, the run must consume at least one space from the input or find the end of the input.

        The handling of spaces and newlines differs from that of C's scanf family: in C, newlines are treated as any other space, and it is never an error when a run of spaces in the format string finds no spaces to consume in the input.

        The verbs behave analogously to those of Printf. For example, %x will scan an integer as a hexadecimal number, and %v will scan the default representation format for the value. The Printf verbs %p and %T and the flags # and + are not implemented. For floating-point and complex values, all valid formatting verbs (%b %e %E %f %F %g %G %x %X and %v) are equivalent and accept both decimal and hexadecimal notation (for example: "2.3e+7", "0x4.5p-8") and digit-separating underscores (for example: "3.14159_26535_89793").

        Input processed by verbs is implicitly space-delimited: the implementation of every verb except %c starts by discarding leading spaces from the remaining input, and the %s verb (and %v reading into a string) stops consuming input at the first space or newline character.

        The familiar base-setting prefixes 0b (binary), 0o and 0 (octal), and 0x (hexadecimal) are accepted when scanning integers without a format or with the %v verb, as are digit-separating underscores.

        Width is interpreted in the input text but there is no syntax for scanning with a precision (no %5.2f, just %5f). If width is provided, it applies after leading spaces are trimmed and specifies the maximum number of runes to read to satisfy the verb. For example,

        Sscanf(" 1234567 ", "%5s%d", &s, &i)
        

        will set s to "12345" and i to 67 while

        Sscanf(" 12 34 567 ", "%5s%d", &s, &i)
        

        will set s to "12" and i to 34.

        In all the scanning functions, a carriage return followed immediately by a newline is treated as a plain newline (\r\n means the same as \n).

        In all the scanning functions, if an operand implements method Scan (that is, it implements the Scanner interface) that method will be used to scan the text for that operand. Also, if the number of arguments scanned is less than the number of arguments provided, an error is returned.

        All arguments to be scanned must be either pointers to basic types or implementations of the Scanner interface.

        Like Scanf and Fscanf, Sscanf need not consume its entire input. There is no way to recover how much of the input string Sscanf used.

        Note: Fscan etc. can read one character (rune) past the input they return, which means that a loop calling a scan routine may skip some of the input. This is usually a problem only when there is no space between input values. If the reader provided to Fscan implements ReadRune, that method will be used to read characters. If the reader also implements UnreadRune, that method will be used to save the character and successive calls will not lose data. To attach ReadRune and UnreadRune methods to a reader without that capability, use bufio.NewReader.

        Example (Formats)

        These examples demonstrate the basics of printing using a format string. Printf, Sprintf, and Fprintf all take a format string that specifies how to format the subsequent arguments. For example, %d (we call that a 'verb') says to print the corresponding argument, which must be an integer (or something containing an integer, such as a slice of ints) in decimal. The verb %v ('v' for 'value') always formats the argument in its default form, just how Print or Println would show it. The special verb %T ('T' for 'Type') prints the type of the argument rather than its value. The examples are not exhaustive; see the package comment for all the details.

        Code:

        // A basic set of examples showing that %v is the default format, in this
        // case decimal for integers, which can be explicitly requested with %d;
        // the output is just what Println generates.
        integer := 23
        // Each of these prints "23" (without the quotes).
        fmt.Println(integer)
        fmt.Printf("%v\n", integer)
        fmt.Printf("%d\n", integer)
        
        // The special verb %T shows the type of an item rather than its value.
        fmt.Printf("%T %T\n", integer, &integer)
        // Result: int *int
        
        // Println(x) is the same as Printf("%v\n", x) so we will use only Printf
        // in the following examples. Each one demonstrates how to format values of
        // a particular type, such as integers or strings. We start each format
        // string with %v to show the default output and follow that with one or
        // more custom formats.
        
        // Booleans print as "true" or "false" with %v or %t.
        truth := true
        fmt.Printf("%v %t\n", truth, truth)
        // Result: true true
        
        // Integers print as decimals with %v and %d,
        // or in hex with %x, octal with %o, or binary with %b.
        answer := 42
        fmt.Printf("%v %d %x %o %b\n", answer, answer, answer, answer, answer)
        // Result: 42 42 2a 52 101010
        
        // Floats have multiple formats: %v and %g print a compact representation,
        // while %f prints a decimal point and %e uses exponential notation. The
        // format %6.2f used here shows how to set the width and precision to
        // control the appearance of a floating-point value. In this instance, 6 is
        // the total width of the printed text for the value (note the extra spaces
        // in the output) and 2 is the number of decimal places to show.
        pi := math.Pi
        fmt.Printf("%v %g %.2f (%6.2f) %e\n", pi, pi, pi, pi, pi)
        // Result: 3.141592653589793 3.141592653589793 3.14 (  3.14) 3.141593e+00
        
        // Complex numbers format as parenthesized pairs of floats, with an 'i'
        // after the imaginary part.
        point := 110.7 + 22.5i
        fmt.Printf("%v %g %.2f %.2e\n", point, point, point, point)
        // Result: (110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i)
        
        // Runes are integers but when printed with %c show the character with that
        // Unicode value. The %q verb shows them as quoted characters, %U as a
        // hex Unicode code point, and %#U as both a code point and a quoted
        // printable form if the rune is printable.
        smile := '😀'
        fmt.Printf("%v %d %c %q %U %#U\n", smile, smile, smile, smile, smile, smile)
        // Result: 128512 128512 😀 '😀' U+1F600 U+1F600 '😀'
        
        // Strings are formatted with %v and %s as-is, with %q as quoted strings,
        // and %#q as backquoted strings.
        placeholders := `foo "bar"`
        fmt.Printf("%v %s %q %#q\n", placeholders, placeholders, placeholders, placeholders)
        // Result: foo "bar" foo "bar" "foo \"bar\"" `foo "bar"`
        
        // Maps formatted with %v show keys and values in their default formats.
        // The %#v form (the # is called a "flag" in this context) shows the map in
        // the Go source format. Maps are printed in a consistent order, sorted
        // by the values of the keys.
        isLegume := map[string]bool{
            "peanut":    true,
            "dachshund": false,
        }
        fmt.Printf("%v %#v\n", isLegume, isLegume)
        // Result: map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true}
        
        // Structs formatted with %v show field values in their default formats.
        // The %+v form shows the fields by name, while %#v formats the struct in
        // Go source format.
        person := struct {
            Name string
            Age  int
        }{"Kim", 22}
        fmt.Printf("%v %+v %#v\n", person, person, person)
        // Result: {Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22}
        
        // The default format for a pointer shows the underlying value preceded by
        // an ampersand. The %p verb prints the pointer value in hex. We use a
        // typed nil for the argument to %p here because the value of any non-nil
        // pointer would change from run to run; run the commented-out Printf
        // call yourself to see.
        pointer := &person
        fmt.Printf("%v %p\n", pointer, (*int)(nil))
        // Result: &{Kim 22} 0x0
        // fmt.Printf("%v %p\n", pointer, pointer)
        // Result: &{Kim 22} 0x010203 // See comment above.
        
        // Arrays and slices are formatted by applying the format to each element.
        greats := [5]string{"Kitano", "Kobayashi", "Kurosawa", "Miyazaki", "Ozu"}
        fmt.Printf("%v %q\n", greats, greats)
        // Result: [Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"]
        
        kGreats := greats[:3]
        fmt.Printf("%v %q %#v\n", kGreats, kGreats, kGreats)
        // Result: [Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"}
        
        // Byte slices are special. Integer verbs like %d print the elements in
        // that format. The %s and %q forms treat the slice like a string. The %x
        // verb has a special form with the space flag that puts a space between
        // the bytes.
        cmd := []byte("a⌘")
        fmt.Printf("%v %d %s %q %x % x\n", cmd, cmd, cmd, cmd, cmd, cmd)
        // Result: [97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98
        
        // Types that implement Stringer are printed the same as strings. Because
        // Stringers return a string, we can print them using a string-specific
        // verb such as %q.
        now := time.Unix(123456789, 0).UTC() // time.Time implements fmt.Stringer.
        fmt.Printf("%v %q\n", now, now)
        // Result: 1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC"
        
        

        Output:

        23
        23
        23
        int *int
        true true
        42 42 2a 52 101010
        3.141592653589793 3.141592653589793 3.14 (  3.14) 3.141593e+00
        (110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i)
        128512 128512 😀 '😀' U+1F600 U+1F600 '😀'
        foo "bar" foo "bar" "foo \"bar\"" `foo "bar"`
        map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true}
        {Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22}
        &{Kim 22} 0x0
        [Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"]
        [Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"}
        [97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98
        1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC"
        

        Example (Printers)

        Print, Println, and Printf lay out their arguments differently. In this example we can compare their behaviors. Println always adds blanks between the items it prints, while Print adds blanks only between non-string arguments and Printf does exactly what it is told. Sprint, Sprintln, Sprintf, Fprint, Fprintln, and Fprintf behave the same as their corresponding Print, Println, and Printf functions shown here.

        Code:

        a, b := 3.0, 4.0
        h := math.Hypot(a, b)
        
        // Print inserts blanks between arguments when neither is a string.
        // It does not add a newline to the output, so we add one explicitly.
        fmt.Print("The vector (", a, b, ") has length ", h, ".\n")
        
        // Println always inserts spaces between its arguments,
        // so it cannot be used to produce the same output as Print in this case;
        // its output has extra spaces.
        // Also, Println always adds a newline to the output.
        fmt.Println("The vector (", a, b, ") has length", h, ".")
        
        // Printf provides complete control but is more complex to use.
        // It does not add a newline to the output, so we add one explicitly
        // at the end of the format specifier string.
        fmt.Printf("The vector (%g %g) has length %g.\n", a, b, h)
        
        

        Output:

        The vector (3 4) has length 5.
        The vector ( 3 4 ) has length 5 .
        The vector (3 4) has length 5.
        

        func Append

        func Append(b []byte, a ...any) []byte

        Append formats using the default formats for its operands, appends the result to the byte slice, and returns the updated slice.

        func Appendf

        func Appendf(b []byte, format string, a ...any) []byte

        Appendf formats according to a format specifier, appends the result to the byte slice, and returns the updated slice.

        func Appendln

        func Appendln(b []byte, a ...any) []byte

        Appendln formats using the default formats for its operands, appends the result to the byte slice, and returns the updated slice. Spaces are always added between operands and a newline is appended.

        func Errorf

        func Errorf(format string, a ...any) error

        Errorf formats according to a format specifier and returns the string as a value that satisfies error.

        If the format specifier includes a %w verb with an error operand, the returned error will implement an Unwrap method returning the operand. If there is more than one %w verb, the returned error will implement an Unwrap method returning a []error containing all the %w operands in the order they appear in the arguments. It is invalid to supply the %w verb with an operand that does not implement the error interface. The %w verb is otherwise a synonym for %v.

        Example

        The Errorf function lets us use formatting features to create descriptive error messages.

        Code:

        const name, id = "bueller", 17
        err := fmt.Errorf("user %q (id %d) not found", name, id)
        fmt.Println(err.Error())
        
        

        Output:

        user "bueller" (id 17) not found
        

        func FormatString

        func FormatString(state State, verb rune) string

        FormatString returns a string representing the fully qualified formatting directive captured by the State, followed by the argument verb. (State does not itself contain the verb.) The result has a leading percent sign followed by any flags, the width, and the precision. Missing flags, width, and precision are omitted. This function allows a Formatter to reconstruct the original directive triggering the call to Format.

        func Fprint

        func Fprint(w io.Writer, a ...any) (n int, err error)

        Fprint formats using the default formats for its operands and writes to w. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.

        Example

        Code:

        const name, age = "Kim", 22
        n, err := fmt.Fprint(os.Stdout, name, " is ", age, " years old.\n")
        
        // The n and err return values from Fprint are
        // those returned by the underlying io.Writer.
        if err != nil {
            fmt.Fprintf(os.Stderr, "Fprint: %v\n", err)
        }
        fmt.Print(n, " bytes written.\n")
        
        

        Output:

        Kim is 22 years old.
        21 bytes written.
        

        func Fprintf

        func Fprintf(w io.Writer, format string, a ...any) (n int, err error)

        Fprintf formats according to a format specifier and writes to w. It returns the number of bytes written and any write error encountered.

        Example

        Code:

        const name, age = "Kim", 22
        n, err := fmt.Fprintf(os.Stdout, "%s is %d years old.\n", name, age)
        
        // The n and err return values from Fprintf are
        // those returned by the underlying io.Writer.
        if err != nil {
            fmt.Fprintf(os.Stderr, "Fprintf: %v\n", err)
        }
        fmt.Printf("%d bytes written.\n", n)
        
        

        Output:

        Kim is 22 years old.
        21 bytes written.
        

        func Fprintln

        func Fprintln(w io.Writer, a ...any) (n int, err error)

        Fprintln formats using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

        Example

        Code:

        const name, age = "Kim", 22
        n, err := fmt.Fprintln(os.Stdout, name, "is", age, "years old.")
        
        // The n and err return values from Fprintln are
        // those returned by the underlying io.Writer.
        if err != nil {
            fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err)
        }
        fmt.Println(n, "bytes written.")
        
        

        Output:

        Kim is 22 years old.
        21 bytes written.
        

        func Fscan

        func Fscan(r io.Reader, a ...any) (n int, err error)

        Fscan scans text read from r, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

        func Fscanf

        func Fscanf(r io.Reader, format string, a ...any) (n int, err error)

        Fscanf scans text read from r, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully parsed. Newlines in the input must match newlines in the format.

        Example

        Code:

        var (
            i int
            b bool
            s string
        )
        r := strings.NewReader("5 true gophers")
        n, err := fmt.Fscanf(r, "%d %t %s", &i, &b, &s)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Fscanf: %v\n", err)
        }
        fmt.Println(i, b, s)
        fmt.Println(n)
        

        Output:

        5 true gophers
        3
        

        func Fscanln

        func Fscanln(r io.Reader, a ...any) (n int, err error)

        Fscanln is similar to Fscan, but stops scanning at a newline and after the final item there must be a newline or EOF.

        Example

        Code:

        s := `dmr 1771 1.61803398875
            ken 271828 3.14159`
        r := strings.NewReader(s)
        var a string
        var b int
        var c float64
        for {
            n, err := fmt.Fscanln(r, &a, &b, &c)
            if err == io.EOF {
                break
            }
            if err != nil {
                panic(err)
            }
            fmt.Printf("%d: %s, %d, %f\n", n, a, b, c)
        }
        

        Output:

        3: dmr, 1771, 1.618034
        3: ken, 271828, 3.141590
        

        func Print

        func Print(a ...any) (n int, err error)

        Print formats using the default formats for its operands and writes to standard output. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.

        Example

        Code:

        const name, age = "Kim", 22
        fmt.Print(name, " is ", age, " years old.\n")
        
        // It is conventional not to worry about any
        // error returned by Print.
        
        

        Output:

        Kim is 22 years old.
        

        func Printf

        func Printf(format string, a ...any) (n int, err error)

        Printf formats according to a format specifier and writes to standard output. It returns the number of bytes written and any write error encountered.

        Example

        Code:

        const name, age = "Kim", 22
        fmt.Printf("%s is %d years old.\n", name, age)
        
        // It is conventional not to worry about any
        // error returned by Printf.
        
        

        Output:

        Kim is 22 years old.
        

        func Println

        func Println(a ...any) (n int, err error)

        Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

        Example

        Code:

        const name, age = "Kim", 22
        fmt.Println(name, "is", age, "years old.")
        
        // It is conventional not to worry about any
        // error returned by Println.
        
        

        Output:

        Kim is 22 years old.
        

        func Scan

        func Scan(a ...any) (n int, err error)

        Scan scans text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

        func Scanf

        func Scanf(format string, a ...any) (n int, err error)

        Scanf scans text read from standard input, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why. Newlines in the input must match newlines in the format. The one exception: the verb %c always scans the next rune in the input, even if it is a space (or tab etc.) or newline.

        func Scanln

        func Scanln(a ...any) (n int, err error)

        Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.

        func Sprint

        func Sprint(a ...any) string

        Sprint formats using the default formats for its operands and returns the resulting string. Spaces are added between operands when neither is a string.

        Example

        Code:

        const name, age = "Kim", 22
        s := fmt.Sprint(name, " is ", age, " years old.\n")
        
        io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
        
        

        Output:

        Kim is 22 years old.
        

        func Sprintf

        func Sprintf(format string, a ...any) string

        Sprintf formats according to a format specifier and returns the resulting string.

        Example

        Code:

        const name, age = "Kim", 22
        s := fmt.Sprintf("%s is %d years old.\n", name, age)
        
        io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
        
        

        Output:

        Kim is 22 years old.
        

        func Sprintln

        func Sprintln(a ...any) string

        Sprintln formats using the default formats for its operands and returns the resulting string. Spaces are always added between operands and a newline is appended.

        Example

        Code:

        const name, age = "Kim", 22
        s := fmt.Sprintln(name, "is", age, "years old.")
        
        io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
        
        

        Output:

        Kim is 22 years old.
        

        func Sscan

        func Sscan(str string, a ...any) (n int, err error)

        Sscan scans the argument string, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

        func Sscanf

        func Sscanf(str string, format string, a ...any) (n int, err error)

        Sscanf scans the argument string, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully parsed. Newlines in the input must match newlines in the format.

        Example

        Code:

        var name string
        var age int
        n, err := fmt.Sscanf("Kim is 22 years old", "%s is %d years old", &name, &age)
        if err != nil {
            panic(err)
        }
        fmt.Printf("%d: %s, %d\n", n, name, age)
        
        

        Output:

        2: Kim, 22
        

        func Sscanln

        func Sscanln(str string, a ...any) (n int, err error)

        Sscanln is similar to Sscan, but stops scanning at a newline and after the final item there must be a newline or EOF.

        type Formatter

        Formatter is implemented by any value that has a Format method. The implementation controls how State and rune are interpreted, and may call Sprint() or Fprint(f) etc. to generate its output.

        type Formatter interface {
            Format(f State, verb rune)
        }

        type GoStringer

        GoStringer is implemented by any value that has a GoString method, which defines the Go syntax for that value. The GoString method is used to print values passed as an operand to a %#v format.

        type GoStringer interface {
            GoString() string
        }

        Example

        Code:

        package fmt_test
        
        import (
            "fmt"
        )
        
        // Address has a City, State and a Country.
        type Address struct {
            City    string
            State   string
            Country string
        }
        
        // Person has a Name, Age and Address.
        type Person struct {
            Name string
            Age  uint
            Addr *Address
        }
        
        // GoString makes Person satisfy the GoStringer interface.
        // The return value is valid Go code that can be used to reproduce the Person struct.
        func (p Person) GoString() string {
            if p.Addr != nil {
                return fmt.Sprintf("Person{Name: %q, Age: %d, Addr: &Address{City: %q, State: %q, Country: %q}}", p.Name, int(p.Age), p.Addr.City, p.Addr.State, p.Addr.Country)
            }
            return fmt.Sprintf("Person{Name: %q, Age: %d}", p.Name, int(p.Age))
        }
        
        func ExampleGoStringer() {
            p1 := Person{
                Name: "Warren",
                Age:  31,
                Addr: &Address{
                    City:    "Denver",
                    State:   "CO",
                    Country: "U.S.A.",
                },
            }
            // If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p1)` would be similar to
            // Person{Name:"Warren", Age:0x1f, Addr:(*main.Address)(0x10448240)}
            fmt.Printf("%#v\n", p1)
        
            p2 := Person{
                Name: "Theia",
                Age:  4,
            }
            // If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p2)` would be similar to
            // Person{Name:"Theia", Age:0x4, Addr:(*main.Address)(nil)}
            fmt.Printf("%#v\n", p2)
        
            // Output:
            // Person{Name: "Warren", Age: 31, Addr: &Address{City: "Denver", State: "CO", Country: "U.S.A."}}
            // Person{Name: "Theia", Age: 4}
        }
        

        type ScanState

        ScanState represents the scanner state passed to custom scanners. Scanners may do rune-at-a-time scanning or ask the ScanState to discover the next space-delimited token.

        type ScanState interface {
            // ReadRune reads the next rune (Unicode code point) from the input.
            // If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will
            // return EOF after returning the first '\n' or when reading beyond
            // the specified width.
            ReadRune() (r rune, size int, err error)
            // UnreadRune causes the next call to ReadRune to return the same rune.
            UnreadRune() error
            // SkipSpace skips space in the input. Newlines are treated appropriately
            // for the operation being performed; see the package documentation
            // for more information.
            SkipSpace()
            // Token skips space in the input if skipSpace is true, then returns the
            // run of Unicode code points c satisfying f(c).  If f is nil,
            // !unicode.IsSpace(c) is used; that is, the token will hold non-space
            // characters. Newlines are treated appropriately for the operation being
            // performed; see the package documentation for more information.
            // The returned slice points to shared data that may be overwritten
            // by the next call to Token, a call to a Scan function using the ScanState
            // as input, or when the calling Scan method returns.
            Token(skipSpace bool, f func(rune) bool) (token []byte, err error)
            // Width returns the value of the width option and whether it has been set.
            // The unit is Unicode code points.
            Width() (wid int, ok bool)
            // Because ReadRune is implemented by the interface, Read should never be
            // called by the scanning routines and a valid implementation of
            // ScanState may choose always to return an error from Read.
            Read(buf []byte) (n int, err error)
        }

        type Scanner

        Scanner is implemented by any value that has a Scan method, which scans the input for the representation of a value and stores the result in the receiver, which must be a pointer to be useful. The Scan method is called for any argument to Scan, Scanf, or Scanln that implements it.

        type Scanner interface {
            Scan(state ScanState, verb rune) error
        }

        type State

        State represents the printer state passed to custom formatters. It provides access to the io.Writer interface plus information about the flags and options for the operand's format specifier.

        type State interface {
            // Write is the function to call to emit formatted output to be printed.
            Write(b []byte) (n int, err error)
            // Width returns the value of the width option and whether it has been set.
            Width() (wid int, ok bool)
            // Precision returns the value of the precision option and whether it has been set.
            Precision() (prec int, ok bool)
        
            // Flag reports whether the flag c, a character, has been set.
            Flag(c int) bool
        }

        type Stringer

        Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print.

        type Stringer interface {
            String() string
        }

        Example

        Code:

        package fmt_test
        
        import (
            "fmt"
        )
        
        // Animal has a Name and an Age to represent an animal.
        type Animal struct {
            Name string
            Age  uint
        }
        
        // String makes Animal satisfy the Stringer interface.
        func (a Animal) String() string {
            return fmt.Sprintf("%v (%d)", a.Name, a.Age)
        }
        
        func ExampleStringer() {
            a := Animal{
                Name: "Gopher",
                Age:  2,
            }
            fmt.Println(a)
            // Output: Gopher (2)
        }
        
        /src/go - Go Documentation Server
        ...

        Directory /src/go

        Name Synopsis
        ..
        ast Package ast declares the types used to represent syntax trees for Go packages.
        build Package build gathers information about Go packages.
        constraint Package constraint implements parsing and evaluation of build constraint lines.
        constant Package constant implements Values representing untyped Go constants and their corresponding operations.
        doc Package doc extracts source code documentation from a Go AST.
        comment Package comment implements parsing and reformatting of Go doc comments, (documentation comments), which are comments that immediately precede a top-level declaration of a package, const, func, type, or var.
        format Package format implements standard formatting of Go source.
        importer Package importer provides access to export data importers.
        parser Package parser implements a parser for Go source files.
        printer Package printer implements printing of AST nodes.
        scanner Package scanner implements a scanner for Go source text.
        token Package token defines constants representing the lexical tokens of the Go programming language and basic operations on tokens (printing, predicates).
        types Package types declares the data types and implements the algorithms for type-checking of Go packages.
        version Package version provides operations on [Go versions] in [Go toolchain name syntax]: strings like "go1.20", "go1.21.0", "go1.22rc2", and "go1.23.4-bigcorp".
        ast - Go Documentation Server
        ...

        Package ast

        import "go/ast"
        Overview
        Index
        Examples

        Overview ▾

        Package ast declares the types used to represent syntax trees for Go packages.

        Index ▾

        func FileExports(src *File) bool
        func FilterDecl(decl Decl, f Filter) bool
        func FilterFile(src *File, f Filter) bool
        func FilterPackage(pkg *Package, f Filter) bool
        func Fprint(w io.Writer, fset *token.FileSet, x any, f FieldFilter) error
        func Inspect(node Node, f func(Node) bool)
        func IsExported(name string) bool
        func IsGenerated(file *File) bool
        func NotNilFilter(_ string, v reflect.Value) bool
        func PackageExports(pkg *Package) bool
        func Print(fset *token.FileSet, x any) error
        func SortImports(fset *token.FileSet, f *File)
        func Walk(v Visitor, node Node)
        type ArrayType
            func (x *ArrayType) End() token.Pos
            func (x *ArrayType) Pos() token.Pos
        type AssignStmt
            func (s *AssignStmt) End() token.Pos
            func (s *AssignStmt) Pos() token.Pos
        type BadDecl
            func (d *BadDecl) End() token.Pos
            func (d *BadDecl) Pos() token.Pos
        type BadExpr
            func (x *BadExpr) End() token.Pos
            func (x *BadExpr) Pos() token.Pos
        type BadStmt
            func (s *BadStmt) End() token.Pos
            func (s *BadStmt) Pos() token.Pos
        type BasicLit
            func (x *BasicLit) End() token.Pos
            func (x *BasicLit) Pos() token.Pos
        type BinaryExpr
            func (x *BinaryExpr) End() token.Pos
            func (x *BinaryExpr) Pos() token.Pos
        type BlockStmt
            func (s *BlockStmt) End() token.Pos
            func (s *BlockStmt) Pos() token.Pos
        type BranchStmt
            func (s *BranchStmt) End() token.Pos
            func (s *BranchStmt) Pos() token.Pos
        type CallExpr
            func (x *CallExpr) End() token.Pos
            func (x *CallExpr) Pos() token.Pos
        type CaseClause
            func (s *CaseClause) End() token.Pos
            func (s *CaseClause) Pos() token.Pos
        type ChanDir
        type ChanType
            func (x *ChanType) End() token.Pos
            func (x *ChanType) Pos() token.Pos
        type CommClause
            func (s *CommClause) End() token.Pos
            func (s *CommClause) Pos() token.Pos
        type Comment
            func (c *Comment) End() token.Pos
            func (c *Comment) Pos() token.Pos
        type CommentGroup
            func (g *CommentGroup) End() token.Pos
            func (g *CommentGroup) Pos() token.Pos
            func (g *CommentGroup) Text() string
        type CommentMap
            func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap
            func (cmap CommentMap) Comments() []*CommentGroup
            func (cmap CommentMap) Filter(node Node) CommentMap
            func (cmap CommentMap) String() string
            func (cmap CommentMap) Update(old, new Node) Node
        type CompositeLit
            func (x *CompositeLit) End() token.Pos
            func (x *CompositeLit) Pos() token.Pos
        type Decl
        type DeclStmt
            func (s *DeclStmt) End() token.Pos
            func (s *DeclStmt) Pos() token.Pos
        type DeferStmt
            func (s *DeferStmt) End() token.Pos
            func (s *DeferStmt) Pos() token.Pos
        type Ellipsis
            func (x *Ellipsis) End() token.Pos
            func (x *Ellipsis) Pos() token.Pos
        type EmptyStmt
            func (s *EmptyStmt) End() token.Pos
            func (s *EmptyStmt) Pos() token.Pos
        type Expr
            func Unparen(e Expr) Expr
        type ExprStmt
            func (s *ExprStmt) End() token.Pos
            func (s *ExprStmt) Pos() token.Pos
        type Field
            func (f *Field) End() token.Pos
            func (f *Field) Pos() token.Pos
        type FieldFilter
        type FieldList
            func (f *FieldList) End() token.Pos
            func (f *FieldList) NumFields() int
            func (f *FieldList) Pos() token.Pos
        type File
            func MergePackageFiles(pkg *Package, mode MergeMode) *File
            func (f *File) End() token.Pos
            func (f *File) Pos() token.Pos
        type Filter
        type ForStmt
            func (s *ForStmt) End() token.Pos
            func (s *ForStmt) Pos() token.Pos
        type FuncDecl
            func (d *FuncDecl) End() token.Pos
            func (d *FuncDecl) Pos() token.Pos
        type FuncLit
            func (x *FuncLit) End() token.Pos
            func (x *FuncLit) Pos() token.Pos
        type FuncType
            func (x *FuncType) End() token.Pos
            func (x *FuncType) Pos() token.Pos
        type GenDecl
            func (d *GenDecl) End() token.Pos
            func (d *GenDecl) Pos() token.Pos
        type GoStmt
            func (s *GoStmt) End() token.Pos
            func (s *GoStmt) Pos() token.Pos
        type Ident
            func NewIdent(name string) *Ident
            func (x *Ident) End() token.Pos
            func (id *Ident) IsExported() bool
            func (x *Ident) Pos() token.Pos
            func (id *Ident) String() string
        type IfStmt
            func (s *IfStmt) End() token.Pos
            func (s *IfStmt) Pos() token.Pos
        type ImportSpec
            func (s *ImportSpec) End() token.Pos
            func (s *ImportSpec) Pos() token.Pos
        type Importer
        type IncDecStmt
            func (s *IncDecStmt) End() token.Pos
            func (s *IncDecStmt) Pos() token.Pos
        type IndexExpr
            func (x *IndexExpr) End() token.Pos
            func (x *IndexExpr) Pos() token.Pos
        type IndexListExpr
            func (x *IndexListExpr) End() token.Pos
            func (x *IndexListExpr) Pos() token.Pos
        type InterfaceType
            func (x *InterfaceType) End() token.Pos
            func (x *InterfaceType) Pos() token.Pos
        type KeyValueExpr
            func (x *KeyValueExpr) End() token.Pos
            func (x *KeyValueExpr) Pos() token.Pos
        type LabeledStmt
            func (s *LabeledStmt) End() token.Pos
            func (s *LabeledStmt) Pos() token.Pos
        type MapType
            func (x *MapType) End() token.Pos
            func (x *MapType) Pos() token.Pos
        type MergeMode
        type Node
        type ObjKind
            func (kind ObjKind) String() string
        type Object
            func NewObj(kind ObjKind, name string) *Object
            func (obj *Object) Pos() token.Pos
        type Package
            func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error)
            func (p *Package) End() token.Pos
            func (p *Package) Pos() token.Pos
        type ParenExpr
            func (x *ParenExpr) End() token.Pos
            func (x *ParenExpr) Pos() token.Pos
        type RangeStmt
            func (s *RangeStmt) End() token.Pos
            func (s *RangeStmt) Pos() token.Pos
        type ReturnStmt
            func (s *ReturnStmt) End() token.Pos
            func (s *ReturnStmt) Pos() token.Pos
        type Scope
            func NewScope(outer *Scope) *Scope
            func (s *Scope) Insert(obj *Object) (alt *Object)
            func (s *Scope) Lookup(name string) *Object
            func (s *Scope) String() string
        type SelectStmt
            func (s *SelectStmt) End() token.Pos
            func (s *SelectStmt) Pos() token.Pos
        type SelectorExpr
            func (x *SelectorExpr) End() token.Pos
            func (x *SelectorExpr) Pos() token.Pos
        type SendStmt
            func (s *SendStmt) End() token.Pos
            func (s *SendStmt) Pos() token.Pos
        type SliceExpr
            func (x *SliceExpr) End() token.Pos
            func (x *SliceExpr) Pos() token.Pos
        type Spec
        type StarExpr
            func (x *StarExpr) End() token.Pos
            func (x *StarExpr) Pos() token.Pos
        type Stmt
        type StructType
            func (x *StructType) End() token.Pos
            func (x *StructType) Pos() token.Pos
        type SwitchStmt
            func (s *SwitchStmt) End() token.Pos
            func (s *SwitchStmt) Pos() token.Pos
        type TypeAssertExpr
            func (x *TypeAssertExpr) End() token.Pos
            func (x *TypeAssertExpr) Pos() token.Pos
        type TypeSpec
            func (s *TypeSpec) End() token.Pos
            func (s *TypeSpec) Pos() token.Pos
        type TypeSwitchStmt
            func (s *TypeSwitchStmt) End() token.Pos
            func (s *TypeSwitchStmt) Pos() token.Pos
        type UnaryExpr
            func (x *UnaryExpr) End() token.Pos
            func (x *UnaryExpr) Pos() token.Pos
        type ValueSpec
            func (s *ValueSpec) End() token.Pos
            func (s *ValueSpec) Pos() token.Pos
        type Visitor

        Examples

        CommentMap
        Inspect
        Print

        Package files

        ast.go commentmap.go filter.go import.go print.go resolve.go scope.go walk.go

        func FileExports

        func FileExports(src *File) bool

        FileExports trims the AST for a Go source file in place such that only exported nodes remain: all top-level identifiers which are not exported and their associated information (such as type, initial value, or function body) are removed. Non-exported fields and methods of exported types are stripped. The [File.Comments] list is not changed.

        FileExports reports whether there are exported declarations.

        func FilterDecl

        func FilterDecl(decl Decl, f Filter) bool

        FilterDecl trims the AST for a Go declaration in place by removing all names (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f.

        FilterDecl reports whether there are any declared names left after filtering.

        func FilterFile

        func FilterFile(src *File, f Filter) bool

        FilterFile trims the AST for a Go file in place by removing all names from top-level declarations (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f. If the declaration is empty afterwards, the declaration is removed from the AST. Import declarations are always removed. The [File.Comments] list is not changed.

        FilterFile reports whether there are any top-level declarations left after filtering.

        func FilterPackage

        func FilterPackage(pkg *Package, f Filter) bool

        FilterPackage trims the AST for a Go package in place by removing all names from top-level declarations (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f. If the declaration is empty afterwards, the declaration is removed from the AST. The pkg.Files list is not changed, so that file names and top-level package comments don't get lost.

        FilterPackage reports whether there are any top-level declarations left after filtering.

        func Fprint

        func Fprint(w io.Writer, fset *token.FileSet, x any, f FieldFilter) error

        Fprint prints the (sub-)tree starting at AST node x to w. If fset != nil, position information is interpreted relative to that file set. Otherwise positions are printed as integer values (file set specific offsets).

        A non-nil FieldFilter f may be provided to control the output: struct fields for which f(fieldname, fieldvalue) is true are printed; all others are filtered from the output. Unexported struct fields are never printed.

        func Inspect

        func Inspect(node Node, f func(Node) bool)

        Inspect traverses an AST in depth-first order: It starts by calling f(node); node must not be nil. If f returns true, Inspect invokes f recursively for each of the non-nil children of node, followed by a call of f(nil).

        Example

        This example demonstrates how to inspect the AST of a Go program.

        Code:

        // src is the input for which we want to inspect the AST.
        src := `
        package p
        const c = 1.0
        var X = f(3.14)*2 + c
        `
        
        // Create the AST by parsing src.
        fset := token.NewFileSet() // positions are relative to fset
        f, err := parser.ParseFile(fset, "src.go", src, 0)
        if err != nil {
            panic(err)
        }
        
        // Inspect the AST and print all identifiers and literals.
        ast.Inspect(f, func(n ast.Node) bool {
            var s string
            switch x := n.(type) {
            case *ast.BasicLit:
                s = x.Value
            case *ast.Ident:
                s = x.Name
            }
            if s != "" {
                fmt.Printf("%s:\t%s\n", fset.Position(n.Pos()), s)
            }
            return true
        })
        
        

        Output:

        src.go:2:9:	p
        src.go:3:7:	c
        src.go:3:11:	1.0
        src.go:4:5:	X
        src.go:4:9:	f
        src.go:4:11:	3.14
        src.go:4:17:	2
        src.go:4:21:	c
        

        func IsExported

        func IsExported(name string) bool

        IsExported reports whether name starts with an upper-case letter.

        func IsGenerated

        func IsGenerated(file *File) bool

        IsGenerated reports whether the file was generated by a program, not handwritten, by detecting the special comment described at https://go.dev/s/generatedcode.

        The syntax tree must have been parsed with the ParseComments flag. Example:

        f, err := parser.ParseFile(fset, filename, src, parser.ParseComments|parser.PackageClauseOnly)
        if err != nil { ... }
        gen := ast.IsGenerated(f)
        

        func NotNilFilter

        func NotNilFilter(_ string, v reflect.Value) bool

        NotNilFilter returns true for field values that are not nil; it returns false otherwise.

        func PackageExports

        func PackageExports(pkg *Package) bool

        PackageExports trims the AST for a Go package in place such that only exported nodes remain. The pkg.Files list is not changed, so that file names and top-level package comments don't get lost.

        PackageExports reports whether there are exported declarations; it returns false otherwise.

        func Print

        func Print(fset *token.FileSet, x any) error

        Print prints x to standard output, skipping nil fields. Print(fset, x) is the same as Fprint(os.Stdout, fset, x, NotNilFilter).

        Example

        This example shows what an AST looks like when printed for debugging.

        Code:

        // src is the input for which we want to print the AST.
        src := `
        package main
        func main() {
            println("Hello, World!")
        }
        `
        
        // Create the AST by parsing src.
        fset := token.NewFileSet() // positions are relative to fset
        f, err := parser.ParseFile(fset, "", src, 0)
        if err != nil {
            panic(err)
        }
        
        // Print the AST.
        ast.Print(fset, f)
        
        

        Output:

             0  *ast.File {
             1  .  Package: 2:1
             2  .  Name: *ast.Ident {
             3  .  .  NamePos: 2:9
             4  .  .  Name: "main"
             5  .  }
             6  .  Decls: []ast.Decl (len = 1) {
             7  .  .  0: *ast.FuncDecl {
             8  .  .  .  Name: *ast.Ident {
             9  .  .  .  .  NamePos: 3:6
            10  .  .  .  .  Name: "main"
            11  .  .  .  .  Obj: *ast.Object {
            12  .  .  .  .  .  Kind: func
            13  .  .  .  .  .  Name: "main"
            14  .  .  .  .  .  Decl: *(obj @ 7)
            15  .  .  .  .  }
            16  .  .  .  }
            17  .  .  .  Type: *ast.FuncType {
            18  .  .  .  .  Func: 3:1
            19  .  .  .  .  Params: *ast.FieldList {
            20  .  .  .  .  .  Opening: 3:10
            21  .  .  .  .  .  Closing: 3:11
            22  .  .  .  .  }
            23  .  .  .  }
            24  .  .  .  Body: *ast.BlockStmt {
            25  .  .  .  .  Lbrace: 3:13
            26  .  .  .  .  List: []ast.Stmt (len = 1) {
            27  .  .  .  .  .  0: *ast.ExprStmt {
            28  .  .  .  .  .  .  X: *ast.CallExpr {
            29  .  .  .  .  .  .  .  Fun: *ast.Ident {
            30  .  .  .  .  .  .  .  .  NamePos: 4:2
            31  .  .  .  .  .  .  .  .  Name: "println"
            32  .  .  .  .  .  .  .  }
            33  .  .  .  .  .  .  .  Lparen: 4:9
            34  .  .  .  .  .  .  .  Args: []ast.Expr (len = 1) {
            35  .  .  .  .  .  .  .  .  0: *ast.BasicLit {
            36  .  .  .  .  .  .  .  .  .  ValuePos: 4:10
            37  .  .  .  .  .  .  .  .  .  Kind: STRING
            38  .  .  .  .  .  .  .  .  .  Value: "\"Hello, World!\""
            39  .  .  .  .  .  .  .  .  }
            40  .  .  .  .  .  .  .  }
            41  .  .  .  .  .  .  .  Ellipsis: -
            42  .  .  .  .  .  .  .  Rparen: 4:25
            43  .  .  .  .  .  .  }
            44  .  .  .  .  .  }
            45  .  .  .  .  }
            46  .  .  .  .  Rbrace: 5:1
            47  .  .  .  }
            48  .  .  }
            49  .  }
            50  .  FileStart: 1:1
            51  .  FileEnd: 5:3
            52  .  Scope: *ast.Scope {
            53  .  .  Objects: map[string]*ast.Object (len = 1) {
            54  .  .  .  "main": *(obj @ 11)
            55  .  .  }
            56  .  }
            57  .  Unresolved: []*ast.Ident (len = 1) {
            58  .  .  0: *(obj @ 29)
            59  .  }
            60  .  GoVersion: ""
            61  }
        

        func SortImports

        func SortImports(fset *token.FileSet, f *File)

        SortImports sorts runs of consecutive import lines in import blocks in f. It also removes duplicate imports when it is possible to do so without data loss.

        func Walk

        func Walk(v Visitor, node Node)

        Walk traverses an AST in depth-first order: It starts by calling v.Visit(node); node must not be nil. If the visitor w returned by v.Visit(node) is not nil, Walk is invoked recursively with visitor w for each of the non-nil children of node, followed by a call of w.Visit(nil).

        type ArrayType

        An ArrayType node represents an array or slice type.

        type ArrayType struct {
            Lbrack token.Pos // position of "["
            Len    Expr      // Ellipsis node for [...]T array types, nil for slice types
            Elt    Expr      // element type
        }
        

        func (*ArrayType) End

        func (x *ArrayType) End() token.Pos

        func (*ArrayType) Pos

        func (x *ArrayType) Pos() token.Pos

        type AssignStmt

        An AssignStmt node represents an assignment or a short variable declaration.

        type AssignStmt struct {
            Lhs    []Expr
            TokPos token.Pos   // position of Tok
            Tok    token.Token // assignment token, DEFINE
            Rhs    []Expr
        }
        

        func (*AssignStmt) End

        func (s *AssignStmt) End() token.Pos

        func (*AssignStmt) Pos

        func (s *AssignStmt) Pos() token.Pos

        type BadDecl

        A BadDecl node is a placeholder for a declaration containing syntax errors for which a correct declaration node cannot be created.

        type BadDecl struct {
            From, To token.Pos // position range of bad declaration
        }
        

        func (*BadDecl) End

        func (d *BadDecl) End() token.Pos

        func (*BadDecl) Pos

        func (d *BadDecl) Pos() token.Pos

        type BadExpr

        A BadExpr node is a placeholder for an expression containing syntax errors for which a correct expression node cannot be created.

        type BadExpr struct {
            From, To token.Pos // position range of bad expression
        }
        

        func (*BadExpr) End

        func (x *BadExpr) End() token.Pos

        func (*BadExpr) Pos

        func (x *BadExpr) Pos() token.Pos

        type BadStmt

        A BadStmt node is a placeholder for statements containing syntax errors for which no correct statement nodes can be created.

        type BadStmt struct {
            From, To token.Pos // position range of bad statement
        }
        

        func (*BadStmt) End

        func (s *BadStmt) End() token.Pos

        func (*BadStmt) Pos

        func (s *BadStmt) Pos() token.Pos

        type BasicLit

        A BasicLit node represents a literal of basic type.

        type BasicLit struct {
            ValuePos token.Pos   // literal position
            Kind     token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING
            Value    string      // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f', "foo" or `\m\n\o`
        }
        

        func (*BasicLit) End

        func (x *BasicLit) End() token.Pos

        func (*BasicLit) Pos

        func (x *BasicLit) Pos() token.Pos

        type BinaryExpr

        A BinaryExpr node represents a binary expression.

        type BinaryExpr struct {
            X     Expr        // left operand
            OpPos token.Pos   // position of Op
            Op    token.Token // operator
            Y     Expr        // right operand
        }
        

        func (*BinaryExpr) End

        func (x *BinaryExpr) End() token.Pos

        func (*BinaryExpr) Pos

        func (x *BinaryExpr) Pos() token.Pos

        type BlockStmt

        A BlockStmt node represents a braced statement list.

        type BlockStmt struct {
            Lbrace token.Pos // position of "{"
            List   []Stmt
            Rbrace token.Pos // position of "}", if any (may be absent due to syntax error)
        }
        

        func (*BlockStmt) End

        func (s *BlockStmt) End() token.Pos

        func (*BlockStmt) Pos

        func (s *BlockStmt) Pos() token.Pos

        type BranchStmt

        A BranchStmt node represents a break, continue, goto, or fallthrough statement.

        type BranchStmt struct {
            TokPos token.Pos   // position of Tok
            Tok    token.Token // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH)
            Label  *Ident      // label name; or nil
        }
        

        func (*BranchStmt) End

        func (s *BranchStmt) End() token.Pos

        func (*BranchStmt) Pos

        func (s *BranchStmt) Pos() token.Pos

        type CallExpr

        A CallExpr node represents an expression followed by an argument list.

        type CallExpr struct {
            Fun      Expr      // function expression
            Lparen   token.Pos // position of "("
            Args     []Expr    // function arguments; or nil
            Ellipsis token.Pos // position of "..." (token.NoPos if there is no "...")
            Rparen   token.Pos // position of ")"
        }
        

        func (*CallExpr) End

        func (x *CallExpr) End() token.Pos

        func (*CallExpr) Pos

        func (x *CallExpr) Pos() token.Pos

        type CaseClause

        A CaseClause represents a case of an expression or type switch statement.

        type CaseClause struct {
            Case  token.Pos // position of "case" or "default" keyword
            List  []Expr    // list of expressions or types; nil means default case
            Colon token.Pos // position of ":"
            Body  []Stmt    // statement list; or nil
        }
        

        func (*CaseClause) End

        func (s *CaseClause) End() token.Pos

        func (*CaseClause) Pos

        func (s *CaseClause) Pos() token.Pos

        type ChanDir

        The direction of a channel type is indicated by a bit mask including one or both of the following constants.

        type ChanDir int
        const (
            SEND ChanDir = 1 << iota
            RECV
        )

        type ChanType

        A ChanType node represents a channel type.

        type ChanType struct {
            Begin token.Pos // position of "chan" keyword or "<-" (whichever comes first)
            Arrow token.Pos // position of "<-" (token.NoPos if there is no "<-")
            Dir   ChanDir   // channel direction
            Value Expr      // value type
        }
        

        func (*ChanType) End

        func (x *ChanType) End() token.Pos

        func (*ChanType) Pos

        func (x *ChanType) Pos() token.Pos

        type CommClause

        A CommClause node represents a case of a select statement.

        type CommClause struct {
            Case  token.Pos // position of "case" or "default" keyword
            Comm  Stmt      // send or receive statement; nil means default case
            Colon token.Pos // position of ":"
            Body  []Stmt    // statement list; or nil
        }
        

        func (*CommClause) End

        func (s *CommClause) End() token.Pos

        func (*CommClause) Pos

        func (s *CommClause) Pos() token.Pos

        type Comment

        A Comment node represents a single //-style or /*-style comment.

        The Text field contains the comment text without carriage returns (\r) that may have been present in the source. Because a comment's end position is computed using len(Text), the position reported by Comment.End does not match the true source end position for comments containing carriage returns.

        type Comment struct {
            Slash token.Pos // position of "/" starting the comment
            Text  string    // comment text (excluding '\n' for //-style comments)
        }
        

        func (*Comment) End

        func (c *Comment) End() token.Pos

        func (*Comment) Pos

        func (c *Comment) Pos() token.Pos

        type CommentGroup

        A CommentGroup represents a sequence of comments with no other tokens and no empty lines between.

        type CommentGroup struct {
            List []*Comment // len(List) > 0
        }
        

        func (*CommentGroup) End

        func (g *CommentGroup) End() token.Pos

        func (*CommentGroup) Pos

        func (g *CommentGroup) Pos() token.Pos

        func (*CommentGroup) Text

        func (g *CommentGroup) Text() string

        Text returns the text of the comment. Comment markers (//, /*, and */), the first space of a line comment, and leading and trailing empty lines are removed. Comment directives like "//line" and "//go:noinline" are also removed. Multiple empty lines are reduced to one, and trailing space on lines is trimmed. Unless the result is empty, it is newline-terminated.

        type CommentMap

        A CommentMap maps an AST node to a list of comment groups associated with it. See NewCommentMap for a description of the association.

        type CommentMap map[Node][]*CommentGroup

        Example

        This example illustrates how to remove a variable declaration in a Go program while maintaining correct comment association using an ast.CommentMap.

        Code:

        // src is the input for which we create the AST that we
        // are going to manipulate.
        src := `
        // This is the package comment.
        package main
        
        // This comment is associated with the hello constant.
        const hello = "Hello, World!" // line comment 1
        
        // This comment is associated with the foo variable.
        var foo = hello // line comment 2
        
        // This comment is associated with the main function.
        func main() {
            fmt.Println(hello) // line comment 3
        }
        `
        
        // Create the AST by parsing src.
        fset := token.NewFileSet() // positions are relative to fset
        f, err := parser.ParseFile(fset, "src.go", src, parser.ParseComments)
        if err != nil {
            panic(err)
        }
        
        // Create an ast.CommentMap from the ast.File's comments.
        // This helps keeping the association between comments
        // and AST nodes.
        cmap := ast.NewCommentMap(fset, f, f.Comments)
        
        // Remove the first variable declaration from the list of declarations.
        for i, decl := range f.Decls {
            if gen, ok := decl.(*ast.GenDecl); ok && gen.Tok == token.VAR {
                copy(f.Decls[i:], f.Decls[i+1:])
                f.Decls = f.Decls[:len(f.Decls)-1]
                break
            }
        }
        
        // Use the comment map to filter comments that don't belong anymore
        // (the comments associated with the variable declaration), and create
        // the new comments list.
        f.Comments = cmap.Filter(f).Comments()
        
        // Print the modified AST.
        var buf strings.Builder
        if err := format.Node(&buf, fset, f); err != nil {
            panic(err)
        }
        fmt.Printf("%s", buf.String())
        
        

        Output:

        // This is the package comment.
        package main
        
        // This comment is associated with the hello constant.
        const hello = "Hello, World!" // line comment 1
        
        // This comment is associated with the main function.
        func main() {
        	fmt.Println(hello) // line comment 3
        }
        

        func NewCommentMap

        func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap

        NewCommentMap creates a new comment map by associating comment groups of the comments list with the nodes of the AST specified by node.

        A comment group g is associated with a node n if:

        • g starts on the same line as n ends
        • g starts on the line immediately following n, and there is at least one empty line after g and before the next node
        • g starts before n and is not associated to the node before n via the previous rules

        NewCommentMap tries to associate a comment group to the "largest" node possible: For instance, if the comment is a line comment trailing an assignment, the comment is associated with the entire assignment rather than just the last operand in the assignment.

        func (CommentMap) Comments

        func (cmap CommentMap) Comments() []*CommentGroup

        Comments returns the list of comment groups in the comment map. The result is sorted in source order.

        func (CommentMap) Filter

        func (cmap CommentMap) Filter(node Node) CommentMap

        Filter returns a new comment map consisting of only those entries of cmap for which a corresponding node exists in the AST specified by node.

        func (CommentMap) String

        func (cmap CommentMap) String() string

        func (CommentMap) Update

        func (cmap CommentMap) Update(old, new Node) Node

        Update replaces an old node in the comment map with the new node and returns the new node. Comments that were associated with the old node are associated with the new node.

        type CompositeLit

        A CompositeLit node represents a composite literal.

        type CompositeLit struct {
            Type       Expr      // literal type; or nil
            Lbrace     token.Pos // position of "{"
            Elts       []Expr    // list of composite elements; or nil
            Rbrace     token.Pos // position of "}"
            Incomplete bool      // true if (source) expressions are missing in the Elts list
        }
        

        func (*CompositeLit) End

        func (x *CompositeLit) End() token.Pos

        func (*CompositeLit) Pos

        func (x *CompositeLit) Pos() token.Pos

        type Decl

        All declaration nodes implement the Decl interface.

        type Decl interface {
            Node
            // contains filtered or unexported methods
        }

        type DeclStmt

        A DeclStmt node represents a declaration in a statement list.

        type DeclStmt struct {
            Decl Decl // *GenDecl with CONST, TYPE, or VAR token
        }
        

        func (*DeclStmt) End

        func (s *DeclStmt) End() token.Pos

        func (*DeclStmt) Pos

        func (s *DeclStmt) Pos() token.Pos

        type DeferStmt

        A DeferStmt node represents a defer statement.

        type DeferStmt struct {
            Defer token.Pos // position of "defer" keyword
            Call  *CallExpr
        }
        

        func (*DeferStmt) End

        func (s *DeferStmt) End() token.Pos

        func (*DeferStmt) Pos

        func (s *DeferStmt) Pos() token.Pos

        type Ellipsis

        An Ellipsis node stands for the "..." type in a parameter list or the "..." length in an array type.

        type Ellipsis struct {
            Ellipsis token.Pos // position of "..."
            Elt      Expr      // ellipsis element type (parameter lists only); or nil
        }
        

        func (*Ellipsis) End

        func (x *Ellipsis) End() token.Pos

        func (*Ellipsis) Pos

        func (x *Ellipsis) Pos() token.Pos

        type EmptyStmt

        An EmptyStmt node represents an empty statement. The "position" of the empty statement is the position of the immediately following (explicit or implicit) semicolon.

        type EmptyStmt struct {
            Semicolon token.Pos // position of following ";"
            Implicit  bool      // if set, ";" was omitted in the source
        }
        

        func (*EmptyStmt) End

        func (s *EmptyStmt) End() token.Pos

        func (*EmptyStmt) Pos

        func (s *EmptyStmt) Pos() token.Pos

        type Expr

        All expression nodes implement the Expr interface.

        type Expr interface {
            Node
            // contains filtered or unexported methods
        }

        func Unparen

        func Unparen(e Expr) Expr

        Unparen returns the expression with any enclosing parentheses removed.

        type ExprStmt

        An ExprStmt node represents a (stand-alone) expression in a statement list.

        type ExprStmt struct {
            X Expr // expression
        }
        

        func (*ExprStmt) End

        func (s *ExprStmt) End() token.Pos

        func (*ExprStmt) Pos

        func (s *ExprStmt) Pos() token.Pos

        type Field

        A Field represents a Field declaration list in a struct type, a method list in an interface type, or a parameter/result declaration in a signature. [Field.Names] is nil for unnamed parameters (parameter lists which only contain types) and embedded struct fields. In the latter case, the field name is the type name.

        type Field struct {
            Doc     *CommentGroup // associated documentation; or nil
            Names   []*Ident      // field/method/(type) parameter names; or nil
            Type    Expr          // field/method/parameter type; or nil
            Tag     *BasicLit     // field tag; or nil
            Comment *CommentGroup // line comments; or nil
        }
        

        func (*Field) End

        func (f *Field) End() token.Pos

        func (*Field) Pos

        func (f *Field) Pos() token.Pos

        type FieldFilter

        A FieldFilter may be provided to Fprint to control the output.

        type FieldFilter func(name string, value reflect.Value) bool

        type FieldList

        A FieldList represents a list of Fields, enclosed by parentheses, curly braces, or square brackets.

        type FieldList struct {
            Opening token.Pos // position of opening parenthesis/brace/bracket, if any
            List    []*Field  // field list; or nil
            Closing token.Pos // position of closing parenthesis/brace/bracket, if any
        }
        

        func (*FieldList) End

        func (f *FieldList) End() token.Pos

        func (*FieldList) NumFields

        func (f *FieldList) NumFields() int

        NumFields returns the number of parameters or struct fields represented by a FieldList.

        func (*FieldList) Pos

        func (f *FieldList) Pos() token.Pos

        type File

        A File node represents a Go source file.

        The Comments list contains all comments in the source file in order of appearance, including the comments that are pointed to from other nodes via Doc and Comment fields.

        For correct printing of source code containing comments (using packages go/format and go/printer), special care must be taken to update comments when a File's syntax tree is modified: For printing, comments are interspersed between tokens based on their position. If syntax tree nodes are removed or moved, relevant comments in their vicinity must also be removed (from the [File.Comments] list) or moved accordingly (by updating their positions). A CommentMap may be used to facilitate some of these operations.

        Whether and how a comment is associated with a node depends on the interpretation of the syntax tree by the manipulating program: Except for Doc and Comment comments directly associated with nodes, the remaining comments are "free-floating" (see also issues #18593, #20744).

        type File struct {
            Doc     *CommentGroup // associated documentation; or nil
            Package token.Pos     // position of "package" keyword
            Name    *Ident        // package name
            Decls   []Decl        // top-level declarations; or nil
        
            FileStart, FileEnd token.Pos       // start and end of entire file
            Scope              *Scope          // package scope (this file only). Deprecated: see Object
            Imports            []*ImportSpec   // imports in this file
            Unresolved         []*Ident        // unresolved identifiers in this file. Deprecated: see Object
            Comments           []*CommentGroup // list of all comments in the source file
            GoVersion          string          // minimum Go version required by //go:build or // +build directives
        }
        

        func MergePackageFiles

        func MergePackageFiles(pkg *Package, mode MergeMode) *File

        MergePackageFiles creates a file AST by merging the ASTs of the files belonging to a package. The mode flags control merging behavior.

        func (*File) End

        func (f *File) End() token.Pos

        End returns the end of the last declaration in the file. (Use FileEnd for the end of the entire file.)

        func (*File) Pos

        func (f *File) Pos() token.Pos

        Pos returns the position of the package declaration. (Use FileStart for the start of the entire file.)

        type Filter

        type Filter func(string) bool

        type ForStmt

        A ForStmt represents a for statement.

        type ForStmt struct {
            For  token.Pos // position of "for" keyword
            Init Stmt      // initialization statement; or nil
            Cond Expr      // condition; or nil
            Post Stmt      // post iteration statement; or nil
            Body *BlockStmt
        }
        

        func (*ForStmt) End

        func (s *ForStmt) End() token.Pos

        func (*ForStmt) Pos

        func (s *ForStmt) Pos() token.Pos

        type FuncDecl

        A FuncDecl node represents a function declaration.

        type FuncDecl struct {
            Doc  *CommentGroup // associated documentation; or nil
            Recv *FieldList    // receiver (methods); or nil (functions)
            Name *Ident        // function/method name
            Type *FuncType     // function signature: type and value parameters, results, and position of "func" keyword
            Body *BlockStmt    // function body; or nil for external (non-Go) function
        }
        

        func (*FuncDecl) End

        func (d *FuncDecl) End() token.Pos

        func (*FuncDecl) Pos

        func (d *FuncDecl) Pos() token.Pos

        type FuncLit

        A FuncLit node represents a function literal.

        type FuncLit struct {
            Type *FuncType  // function type
            Body *BlockStmt // function body
        }
        

        func (*FuncLit) End

        func (x *FuncLit) End() token.Pos

        func (*FuncLit) Pos

        func (x *FuncLit) Pos() token.Pos

        type FuncType

        A FuncType node represents a function type.

        type FuncType struct {
            Func       token.Pos  // position of "func" keyword (token.NoPos if there is no "func")
            TypeParams *FieldList // type parameters; or nil
            Params     *FieldList // (incoming) parameters; non-nil
            Results    *FieldList // (outgoing) results; or nil
        }
        

        func (*FuncType) End

        func (x *FuncType) End() token.Pos

        func (*FuncType) Pos

        func (x *FuncType) Pos() token.Pos

        type GenDecl

        A GenDecl node (generic declaration node) represents an import, constant, type or variable declaration. A valid Lparen position (Lparen.IsValid()) indicates a parenthesized declaration.

        Relationship between Tok value and Specs element type:

        token.IMPORT  *ImportSpec
        token.CONST   *ValueSpec
        token.TYPE    *TypeSpec
        token.VAR     *ValueSpec
        
        type GenDecl struct {
            Doc    *CommentGroup // associated documentation; or nil
            TokPos token.Pos     // position of Tok
            Tok    token.Token   // IMPORT, CONST, TYPE, or VAR
            Lparen token.Pos     // position of '(', if any
            Specs  []Spec
            Rparen token.Pos // position of ')', if any
        }
        

        func (*GenDecl) End

        func (d *GenDecl) End() token.Pos

        func (*GenDecl) Pos

        func (d *GenDecl) Pos() token.Pos

        type GoStmt

        A GoStmt node represents a go statement.

        type GoStmt struct {
            Go   token.Pos // position of "go" keyword
            Call *CallExpr
        }
        

        func (*GoStmt) End

        func (s *GoStmt) End() token.Pos

        func (*GoStmt) Pos

        func (s *GoStmt) Pos() token.Pos

        type Ident

        An Ident node represents an identifier.

        type Ident struct {
            NamePos token.Pos // identifier position
            Name    string    // identifier name
            Obj     *Object   // denoted object, or nil. Deprecated: see Object.
        }
        

        func NewIdent

        func NewIdent(name string) *Ident

        NewIdent creates a new Ident without position. Useful for ASTs generated by code other than the Go parser.

        func (*Ident) End

        func (x *Ident) End() token.Pos

        func (*Ident) IsExported

        func (id *Ident) IsExported() bool

        IsExported reports whether id starts with an upper-case letter.

        func (*Ident) Pos

        func (x *Ident) Pos() token.Pos

        func (*Ident) String

        func (id *Ident) String() string

        type IfStmt

        An IfStmt node represents an if statement.

        type IfStmt struct {
            If   token.Pos // position of "if" keyword
            Init Stmt      // initialization statement; or nil
            Cond Expr      // condition
            Body *BlockStmt
            Else Stmt // else branch; or nil
        }
        

        func (*IfStmt) End

        func (s *IfStmt) End() token.Pos

        func (*IfStmt) Pos

        func (s *IfStmt) Pos() token.Pos

        type ImportSpec

        An ImportSpec node represents a single package import.

        type ImportSpec struct {
            Doc     *CommentGroup // associated documentation; or nil
            Name    *Ident        // local package name (including "."); or nil
            Path    *BasicLit     // import path
            Comment *CommentGroup // line comments; or nil
            EndPos  token.Pos     // end of spec (overrides Path.Pos if nonzero)
        }
        

        func (*ImportSpec) End

        func (s *ImportSpec) End() token.Pos

        func (*ImportSpec) Pos

        func (s *ImportSpec) Pos() token.Pos

        type Importer

        An Importer resolves import paths to package Objects. The imports map records the packages already imported, indexed by package id (canonical import path). An Importer must determine the canonical import path and check the map to see if it is already present in the imports map. If so, the Importer can return the map entry. Otherwise, the Importer should load the package data for the given path into a new *Object (pkg), record pkg in the imports map, and then return pkg.

        Deprecated: use the type checker go/types instead; see Object.

        type Importer func(imports map[string]*Object, path string) (pkg *Object, err error)

        type IncDecStmt

        An IncDecStmt node represents an increment or decrement statement.

        type IncDecStmt struct {
            X      Expr
            TokPos token.Pos   // position of Tok
            Tok    token.Token // INC or DEC
        }
        

        func (*IncDecStmt) End

        func (s *IncDecStmt) End() token.Pos

        func (*IncDecStmt) Pos

        func (s *IncDecStmt) Pos() token.Pos

        type IndexExpr

        An IndexExpr node represents an expression followed by an index.

        type IndexExpr struct {
            X      Expr      // expression
            Lbrack token.Pos // position of "["
            Index  Expr      // index expression
            Rbrack token.Pos // position of "]"
        }
        

        func (*IndexExpr) End

        func (x *IndexExpr) End() token.Pos

        func (*IndexExpr) Pos

        func (x *IndexExpr) Pos() token.Pos

        type IndexListExpr

        An IndexListExpr node represents an expression followed by multiple indices.

        type IndexListExpr struct {
            X       Expr      // expression
            Lbrack  token.Pos // position of "["
            Indices []Expr    // index expressions
            Rbrack  token.Pos // position of "]"
        }
        

        func (*IndexListExpr) End

        func (x *IndexListExpr) End() token.Pos

        func (*IndexListExpr) Pos

        func (x *IndexListExpr) Pos() token.Pos

        type InterfaceType

        An InterfaceType node represents an interface type.

        type InterfaceType struct {
            Interface  token.Pos  // position of "interface" keyword
            Methods    *FieldList // list of embedded interfaces, methods, or types
            Incomplete bool       // true if (source) methods or types are missing in the Methods list
        }
        

        func (*InterfaceType) End

        func (x *InterfaceType) End() token.Pos

        func (*InterfaceType) Pos

        func (x *InterfaceType) Pos() token.Pos

        type KeyValueExpr

        A KeyValueExpr node represents (key : value) pairs in composite literals.

        type KeyValueExpr struct {
            Key   Expr
            Colon token.Pos // position of ":"
            Value Expr
        }
        

        func (*KeyValueExpr) End

        func (x *KeyValueExpr) End() token.Pos

        func (*KeyValueExpr) Pos

        func (x *KeyValueExpr) Pos() token.Pos

        type LabeledStmt

        A LabeledStmt node represents a labeled statement.

        type LabeledStmt struct {
            Label *Ident
            Colon token.Pos // position of ":"
            Stmt  Stmt
        }
        

        func (*LabeledStmt) End

        func (s *LabeledStmt) End() token.Pos

        func (*LabeledStmt) Pos

        func (s *LabeledStmt) Pos() token.Pos

        type MapType

        A MapType node represents a map type.

        type MapType struct {
            Map   token.Pos // position of "map" keyword
            Key   Expr
            Value Expr
        }
        

        func (*MapType) End

        func (x *MapType) End() token.Pos

        func (*MapType) Pos

        func (x *MapType) Pos() token.Pos

        type MergeMode

        The MergeMode flags control the behavior of MergePackageFiles.

        type MergeMode uint
        const (
            // If set, duplicate function declarations are excluded.
            FilterFuncDuplicates MergeMode = 1 << iota
            // If set, comments that are not associated with a specific
            // AST node (as Doc or Comment) are excluded.
            FilterUnassociatedComments
            // If set, duplicate import declarations are excluded.
            FilterImportDuplicates
        )

        type Node

        All node types implement the Node interface.

        type Node interface {
            Pos() token.Pos // position of first character belonging to the node
            End() token.Pos // position of first character immediately after the node
        }

        type ObjKind

        ObjKind describes what an object represents.

        type ObjKind int

        The list of possible Object kinds.

        const (
            Bad ObjKind = iota // for error handling
            Pkg                // package
            Con                // constant
            Typ                // type
            Var                // variable
            Fun                // function or method
            Lbl                // label
        )

        func (ObjKind) String

        func (kind ObjKind) String() string

        type Object

        An Object describes a named language entity such as a package, constant, type, variable, function (incl. methods), or label.

        The Data fields contains object-specific data:

        Kind    Data type         Data value
        Pkg     *Scope            package scope
        Con     int               iota for the respective declaration
        

        Deprecated: The relationship between Idents and Objects cannot be correctly computed without type information. For example, the expression T{K: 0} may denote a struct, map, slice, or array literal, depending on the type of T. If T is a struct, then K refers to a field of T, whereas for the other types it refers to a value in the environment.

        New programs should set the [parser.SkipObjectResolution] parser flag to disable syntactic object resolution (which also saves CPU and memory), and instead use the type checker go/types if object resolution is desired. See the Defs, Uses, and Implicits fields of the [types.Info] struct for details.

        type Object struct {
            Kind ObjKind
            Name string // declared name
            Decl any    // corresponding Field, XxxSpec, FuncDecl, LabeledStmt, AssignStmt, Scope; or nil
            Data any    // object-specific data; or nil
            Type any    // placeholder for type information; may be nil
        }
        

        func NewObj

        func NewObj(kind ObjKind, name string) *Object

        NewObj creates a new object of a given kind and name.

        func (*Object) Pos

        func (obj *Object) Pos() token.Pos

        Pos computes the source position of the declaration of an object name. The result may be an invalid position if it cannot be computed (obj.Decl may be nil or not correct).

        type Package

        A Package node represents a set of source files collectively building a Go package.

        Deprecated: use the type checker go/types instead; see Object.

        type Package struct {
            Name    string             // package name
            Scope   *Scope             // package scope across all files
            Imports map[string]*Object // map of package id -> package object
            Files   map[string]*File   // Go source files by filename
        }
        

        func NewPackage

        func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error)

        NewPackage creates a new Package node from a set of File nodes. It resolves unresolved identifiers across files and updates each file's Unresolved list accordingly. If a non-nil importer and universe scope are provided, they are used to resolve identifiers not declared in any of the package files. Any remaining unresolved identifiers are reported as undeclared. If the files belong to different packages, one package name is selected and files with different package names are reported and then ignored. The result is a package node and a scanner.ErrorList if there were errors.

        Deprecated: use the type checker go/types instead; see Object.

        func (*Package) End

        func (p *Package) End() token.Pos

        func (*Package) Pos

        func (p *Package) Pos() token.Pos

        type ParenExpr

        A ParenExpr node represents a parenthesized expression.

        type ParenExpr struct {
            Lparen token.Pos // position of "("
            X      Expr      // parenthesized expression
            Rparen token.Pos // position of ")"
        }
        

        func (*ParenExpr) End

        func (x *ParenExpr) End() token.Pos

        func (*ParenExpr) Pos

        func (x *ParenExpr) Pos() token.Pos

        type RangeStmt

        A RangeStmt represents a for statement with a range clause.

        type RangeStmt struct {
            For        token.Pos   // position of "for" keyword
            Key, Value Expr        // Key, Value may be nil
            TokPos     token.Pos   // position of Tok; invalid if Key == nil
            Tok        token.Token // ILLEGAL if Key == nil, ASSIGN, DEFINE
            Range      token.Pos   // position of "range" keyword
            X          Expr        // value to range over
            Body       *BlockStmt
        }
        

        func (*RangeStmt) End

        func (s *RangeStmt) End() token.Pos

        func (*RangeStmt) Pos

        func (s *RangeStmt) Pos() token.Pos

        type ReturnStmt

        A ReturnStmt node represents a return statement.

        type ReturnStmt struct {
            Return  token.Pos // position of "return" keyword
            Results []Expr    // result expressions; or nil
        }
        

        func (*ReturnStmt) End

        func (s *ReturnStmt) End() token.Pos

        func (*ReturnStmt) Pos

        func (s *ReturnStmt) Pos() token.Pos

        type Scope

        A Scope maintains the set of named language entities declared in the scope and a link to the immediately surrounding (outer) scope.

        Deprecated: use the type checker go/types instead; see Object.

        type Scope struct {
            Outer   *Scope
            Objects map[string]*Object
        }
        

        func NewScope

        func NewScope(outer *Scope) *Scope

        NewScope creates a new scope nested in the outer scope.

        func (*Scope) Insert

        func (s *Scope) Insert(obj *Object) (alt *Object)

        Insert attempts to insert a named object obj into the scope s. If the scope already contains an object alt with the same name, Insert leaves the scope unchanged and returns alt. Otherwise it inserts obj and returns nil.

        func (*Scope) Lookup

        func (s *Scope) Lookup(name string) *Object

        Lookup returns the object with the given name if it is found in scope s, otherwise it returns nil. Outer scopes are ignored.

        func (*Scope) String

        func (s *Scope) String() string

        Debugging support

        type SelectStmt

        A SelectStmt node represents a select statement.

        type SelectStmt struct {
            Select token.Pos  // position of "select" keyword
            Body   *BlockStmt // CommClauses only
        }
        

        func (*SelectStmt) End

        func (s *SelectStmt) End() token.Pos

        func (*SelectStmt) Pos

        func (s *SelectStmt) Pos() token.Pos

        type SelectorExpr

        A SelectorExpr node represents an expression followed by a selector.

        type SelectorExpr struct {
            X   Expr   // expression
            Sel *Ident // field selector
        }
        

        func (*SelectorExpr) End

        func (x *SelectorExpr) End() token.Pos

        func (*SelectorExpr) Pos

        func (x *SelectorExpr) Pos() token.Pos

        type SendStmt

        A SendStmt node represents a send statement.

        type SendStmt struct {
            Chan  Expr
            Arrow token.Pos // position of "<-"
            Value Expr
        }
        

        func (*SendStmt) End

        func (s *SendStmt) End() token.Pos

        func (*SendStmt) Pos

        func (s *SendStmt) Pos() token.Pos

        type SliceExpr

        A SliceExpr node represents an expression followed by slice indices.

        type SliceExpr struct {
            X      Expr      // expression
            Lbrack token.Pos // position of "["
            Low    Expr      // begin of slice range; or nil
            High   Expr      // end of slice range; or nil
            Max    Expr      // maximum capacity of slice; or nil
            Slice3 bool      // true if 3-index slice (2 colons present)
            Rbrack token.Pos // position of "]"
        }
        

        func (*SliceExpr) End

        func (x *SliceExpr) End() token.Pos

        func (*SliceExpr) Pos

        func (x *SliceExpr) Pos() token.Pos

        type Spec

        The Spec type stands for any of *ImportSpec, *ValueSpec, and *TypeSpec.

        type Spec interface {
            Node
            // contains filtered or unexported methods
        }

        type StarExpr

        A StarExpr node represents an expression of the form "*" Expression. Semantically it could be a unary "*" expression, or a pointer type.

        type StarExpr struct {
            Star token.Pos // position of "*"
            X    Expr      // operand
        }
        

        func (*StarExpr) End

        func (x *StarExpr) End() token.Pos

        func (*StarExpr) Pos

        func (x *StarExpr) Pos() token.Pos

        type Stmt

        All statement nodes implement the Stmt interface.

        type Stmt interface {
            Node
            // contains filtered or unexported methods
        }

        type StructType

        A StructType node represents a struct type.

        type StructType struct {
            Struct     token.Pos  // position of "struct" keyword
            Fields     *FieldList // list of field declarations
            Incomplete bool       // true if (source) fields are missing in the Fields list
        }
        

        func (*StructType) End

        func (x *StructType) End() token.Pos

        func (*StructType) Pos

        func (x *StructType) Pos() token.Pos

        type SwitchStmt

        A SwitchStmt node represents an expression switch statement.

        type SwitchStmt struct {
            Switch token.Pos  // position of "switch" keyword
            Init   Stmt       // initialization statement; or nil
            Tag    Expr       // tag expression; or nil
            Body   *BlockStmt // CaseClauses only
        }
        

        func (*SwitchStmt) End

        func (s *SwitchStmt) End() token.Pos

        func (*SwitchStmt) Pos

        func (s *SwitchStmt) Pos() token.Pos

        type TypeAssertExpr

        A TypeAssertExpr node represents an expression followed by a type assertion.

        type TypeAssertExpr struct {
            X      Expr      // expression
            Lparen token.Pos // position of "("
            Type   Expr      // asserted type; nil means type switch X.(type)
            Rparen token.Pos // position of ")"
        }
        

        func (*TypeAssertExpr) End

        func (x *TypeAssertExpr) End() token.Pos

        func (*TypeAssertExpr) Pos

        func (x *TypeAssertExpr) Pos() token.Pos

        type TypeSpec

        A TypeSpec node represents a type declaration (TypeSpec production).

        type TypeSpec struct {
            Doc        *CommentGroup // associated documentation; or nil
            Name       *Ident        // type name
            TypeParams *FieldList    // type parameters; or nil
            Assign     token.Pos     // position of '=', if any
            Type       Expr          // *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes
            Comment    *CommentGroup // line comments; or nil
        }
        

        func (*TypeSpec) End

        func (s *TypeSpec) End() token.Pos

        func (*TypeSpec) Pos

        func (s *TypeSpec) Pos() token.Pos

        type TypeSwitchStmt

        A TypeSwitchStmt node represents a type switch statement.

        type TypeSwitchStmt struct {
            Switch token.Pos  // position of "switch" keyword
            Init   Stmt       // initialization statement; or nil
            Assign Stmt       // x := y.(type) or y.(type)
            Body   *BlockStmt // CaseClauses only
        }
        

        func (*TypeSwitchStmt) End

        func (s *TypeSwitchStmt) End() token.Pos

        func (*TypeSwitchStmt) Pos

        func (s *TypeSwitchStmt) Pos() token.Pos

        type UnaryExpr

        A UnaryExpr node represents a unary expression. Unary "*" expressions are represented via StarExpr nodes.

        type UnaryExpr struct {
            OpPos token.Pos   // position of Op
            Op    token.Token // operator
            X     Expr        // operand
        }
        

        func (*UnaryExpr) End

        func (x *UnaryExpr) End() token.Pos

        func (*UnaryExpr) Pos

        func (x *UnaryExpr) Pos() token.Pos

        type ValueSpec

        A ValueSpec node represents a constant or variable declaration (ConstSpec or VarSpec production).

        type ValueSpec struct {
            Doc     *CommentGroup // associated documentation; or nil
            Names   []*Ident      // value names (len(Names) > 0)
            Type    Expr          // value type; or nil
            Values  []Expr        // initial values; or nil
            Comment *CommentGroup // line comments; or nil
        }
        

        func (*ValueSpec) End

        func (s *ValueSpec) End() token.Pos

        func (*ValueSpec) Pos

        func (s *ValueSpec) Pos() token.Pos

        type Visitor

        A Visitor's Visit method is invoked for each node encountered by Walk. If the result visitor w is not nil, Walk visits each of the children of node with the visitor w, followed by a call of w.Visit(nil).

        type Visitor interface {
            Visit(node Node) (w Visitor)
        }
        build - Go Documentation Server
        ...

        Package build

        import "go/build"
        Overview
        Index
        Subdirectories

        Overview ▾

        Package build gathers information about Go packages.

        Go Path

        The Go path is a list of directory trees containing Go source code. It is consulted to resolve imports that cannot be found in the standard Go tree. The default path is the value of the GOPATH environment variable, interpreted as a path list appropriate to the operating system (on Unix, the variable is a colon-separated string; on Windows, a semicolon-separated string; on Plan 9, a list).

        Each directory listed in the Go path must have a prescribed structure:

        The src/ directory holds source code. The path below 'src' determines the import path or executable name.

        The pkg/ directory holds installed package objects. As in the Go tree, each target operating system and architecture pair has its own subdirectory of pkg (pkg/GOOS_GOARCH).

        If DIR is a directory listed in the Go path, a package with source in DIR/src/foo/bar can be imported as "foo/bar" and has its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a" (or, for gccgo, "DIR/pkg/gccgo/foo/libbar.a").

        The bin/ directory holds compiled commands. Each command is named for its source directory, but only using the final element, not the entire path. That is, the command with source in DIR/src/foo/quux is installed into DIR/bin/quux, not DIR/bin/foo/quux. The foo/ is stripped so that you can add DIR/bin to your PATH to get at the installed commands.

        Here's an example directory layout:

        GOPATH=/home/user/gocode
        
        /home/user/gocode/
            src/
                foo/
                    bar/               (go code in package bar)
                        x.go
                    quux/              (go code in package main)
                        y.go
            bin/
                quux                   (installed command)
            pkg/
                linux_amd64/
                    foo/
                        bar.a          (installed package object)
        

        Build Constraints

        A build constraint, also known as a build tag, is a condition under which a file should be included in the package. Build constraints are given by a line comment that begins

        //go:build
        

        Build constraints may also be part of a file's name (for example, source_windows.go will only be included if the target operating system is windows).

        See 'go help buildconstraint' (https://golang.org/cmd/go/#hdr-Build_constraints) for details.

        Binary-Only Packages

        In Go 1.12 and earlier, it was possible to distribute packages in binary form without including the source code used for compiling the package. The package was distributed with a source file not excluded by build constraints and containing a "//go:binary-only-package" comment. Like a build constraint, this comment appeared at the top of a file, preceded only by blank lines and other line comments and with a blank line following the comment, to separate it from the package documentation. Unlike build constraints, this comment is only recognized in non-test Go source files.

        The minimal source code for a binary-only package was therefore:

        //go:binary-only-package
        
        package mypkg
        

        The source code could include additional Go code. That code was never compiled but would be processed by tools like godoc and might be useful as end-user documentation.

        "go build" and other commands no longer support binary-only-packages. Import and ImportDir will still set the BinaryOnly flag in packages containing these comments for use in tools and error messages.

        Variables

        ToolDir is the directory containing build tools.

        var ToolDir = getToolDir()

        func ArchChar

        func ArchChar(goarch string) (string, error)

        ArchChar returns "?" and an error. In earlier versions of Go, the returned string was used to derive the compiler and linker tool names, the default object file suffix, and the default linker output name. As of Go 1.5, those strings no longer vary by architecture; they are compile, link, .o, and a.out, respectively.

        func IsLocalImport

        func IsLocalImport(path string) bool

        IsLocalImport reports whether the import path is a local import path, like ".", "..", "./foo", or "../foo".

        type Context

        A Context specifies the supporting context for a build.

        type Context struct {
            GOARCH string // target architecture
            GOOS   string // target operating system
            GOROOT string // Go root
            GOPATH string // Go paths
        
            // Dir is the caller's working directory, or the empty string to use
            // the current directory of the running process. In module mode, this is used
            // to locate the main module.
            //
            // If Dir is non-empty, directories passed to Import and ImportDir must
            // be absolute.
            Dir string
        
            CgoEnabled  bool   // whether cgo files are included
            UseAllFiles bool   // use files regardless of go:build lines, file names
            Compiler    string // compiler to assume when computing target paths
        
            // The build, tool, and release tags specify build constraints
            // that should be considered satisfied when processing go:build lines.
            // Clients creating a new context may customize BuildTags, which
            // defaults to empty, but it is usually an error to customize ToolTags or ReleaseTags.
            // ToolTags defaults to build tags appropriate to the current Go toolchain configuration.
            // ReleaseTags defaults to the list of Go releases the current release is compatible with.
            // BuildTags is not set for the Default build Context.
            // In addition to the BuildTags, ToolTags, and ReleaseTags, build constraints
            // consider the values of GOARCH and GOOS as satisfied tags.
            // The last element in ReleaseTags is assumed to be the current release.
            BuildTags   []string
            ToolTags    []string
            ReleaseTags []string
        
            // The install suffix specifies a suffix to use in the name of the installation
            // directory. By default it is empty, but custom builds that need to keep
            // their outputs separate can set InstallSuffix to do so. For example, when
            // using the race detector, the go command uses InstallSuffix = "race", so
            // that on a Linux/386 system, packages are written to a directory named
            // "linux_386_race" instead of the usual "linux_386".
            InstallSuffix string
        
            // JoinPath joins the sequence of path fragments into a single path.
            // If JoinPath is nil, Import uses filepath.Join.
            JoinPath func(elem ...string) string
        
            // SplitPathList splits the path list into a slice of individual paths.
            // If SplitPathList is nil, Import uses filepath.SplitList.
            SplitPathList func(list string) []string
        
            // IsAbsPath reports whether path is an absolute path.
            // If IsAbsPath is nil, Import uses filepath.IsAbs.
            IsAbsPath func(path string) bool
        
            // IsDir reports whether the path names a directory.
            // If IsDir is nil, Import calls os.Stat and uses the result's IsDir method.
            IsDir func(path string) bool
        
            // HasSubdir reports whether dir is lexically a subdirectory of
            // root, perhaps multiple levels below. It does not try to check
            // whether dir exists.
            // If so, HasSubdir sets rel to a slash-separated path that
            // can be joined to root to produce a path equivalent to dir.
            // If HasSubdir is nil, Import uses an implementation built on
            // filepath.EvalSymlinks.
            HasSubdir func(root, dir string) (rel string, ok bool)
        
            // ReadDir returns a slice of fs.FileInfo, sorted by Name,
            // describing the content of the named directory.
            // If ReadDir is nil, Import uses os.ReadDir.
            ReadDir func(dir string) ([]fs.FileInfo, error)
        
            // OpenFile opens a file (not a directory) for reading.
            // If OpenFile is nil, Import uses os.Open.
            OpenFile func(path string) (io.ReadCloser, error)
        }
        

        Default is the default Context for builds. It uses the GOARCH, GOOS, GOROOT, and GOPATH environment variables if set, or else the compiled code's GOARCH, GOOS, and GOROOT.

        var Default Context = defaultContext()

        func (*Context) Import

        func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error)

        Import returns details about the Go package named by the import path, interpreting local import paths relative to the srcDir directory. If the path is a local import path naming a package that can be imported using a standard import path, the returned package will set p.ImportPath to that path.

        In the directory containing the package, .go, .c, .h, and .s files are considered part of the package except for:

        • .go files in package documentation
        • files starting with _ or . (likely editor temporary files)
        • files with build constraints not satisfied by the context

        If an error occurs, Import returns a non-nil error and a non-nil *Package containing partial information.

        func (*Context) ImportDir

        func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error)

        ImportDir is like Import but processes the Go package found in the named directory.

        func (*Context) MatchFile

        func (ctxt *Context) MatchFile(dir, name string) (match bool, err error)

        MatchFile reports whether the file with the given name in the given directory matches the context and would be included in a Package created by ImportDir of that directory.

        MatchFile considers the name of the file and may use ctxt.OpenFile to read some or all of the file's content.

        func (*Context) SrcDirs

        func (ctxt *Context) SrcDirs() []string

        SrcDirs returns a list of package source root directories. It draws from the current Go root and Go path but omits directories that do not exist.

        type Directive

        A Directive is a Go directive comment (//go:zzz...) found in a source file.

        type Directive struct {
            Text string         // full line comment including leading slashes
            Pos  token.Position // position of comment
        }
        

        type ImportMode

        An ImportMode controls the behavior of the Import method.

        type ImportMode uint
        const (
            // If FindOnly is set, Import stops after locating the directory
            // that should contain the sources for a package. It does not
            // read any files in the directory.
            FindOnly ImportMode = 1 << iota
        
            // If AllowBinary is set, Import can be satisfied by a compiled
            // package object without corresponding sources.
            //
            // Deprecated:
            // The supported way to create a compiled-only package is to
            // write source code containing a //go:binary-only-package comment at
            // the top of the file. Such a package will be recognized
            // regardless of this flag setting (because it has source code)
            // and will have BinaryOnly set to true in the returned Package.
            AllowBinary
        
            // If ImportComment is set, parse import comments on package statements.
            // Import returns an error if it finds a comment it cannot understand
            // or finds conflicting comments in multiple source files.
            // See golang.org/s/go14customimport for more information.
            ImportComment
        
            // By default, Import searches vendor directories
            // that apply in the given source directory before searching
            // the GOROOT and GOPATH roots.
            // If an Import finds and returns a package using a vendor
            // directory, the resulting ImportPath is the complete path
            // to the package, including the path elements leading up
            // to and including "vendor".
            // For example, if Import("y", "x/subdir", 0) finds
            // "x/vendor/y", the returned package's ImportPath is "x/vendor/y",
            // not plain "y".
            // See golang.org/s/go15vendor for more information.
            //
            // Setting IgnoreVendor ignores vendor directories.
            //
            // In contrast to the package's ImportPath,
            // the returned package's Imports, TestImports, and XTestImports
            // are always the exact import paths from the source files:
            // Import makes no attempt to resolve or check those paths.
            IgnoreVendor
        )

        type MultiplePackageError

        MultiplePackageError describes a directory containing multiple buildable Go source files for multiple packages.

        type MultiplePackageError struct {
            Dir      string   // directory containing files
            Packages []string // package names found
            Files    []string // corresponding files: Files[i] declares package Packages[i]
        }
        

        func (*MultiplePackageError) Error

        func (e *MultiplePackageError) Error() string

        type NoGoError

        NoGoError is the error used by Import to describe a directory containing no buildable Go source files. (It may still contain test files, files hidden by build tags, and so on.)

        type NoGoError struct {
            Dir string
        }
        

        func (*NoGoError) Error

        func (e *NoGoError) Error() string

        type Package

        A Package describes the Go package found in a directory.

        type Package struct {
            Dir           string   // directory containing package sources
            Name          string   // package name
            ImportComment string   // path in import comment on package statement
            Doc           string   // documentation synopsis
            ImportPath    string   // import path of package ("" if unknown)
            Root          string   // root of Go tree where this package lives
            SrcRoot       string   // package source root directory ("" if unknown)
            PkgRoot       string   // package install root directory ("" if unknown)
            PkgTargetRoot string   // architecture dependent install root directory ("" if unknown)
            BinDir        string   // command install directory ("" if unknown)
            Goroot        bool     // package found in Go root
            PkgObj        string   // installed .a file
            AllTags       []string // tags that can influence file selection in this directory
            ConflictDir   string   // this directory shadows Dir in $GOPATH
            BinaryOnly    bool     // cannot be rebuilt from source (has //go:binary-only-package comment)
        
            // Source files
            GoFiles           []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
            CgoFiles          []string // .go source files that import "C"
            IgnoredGoFiles    []string // .go source files ignored for this build (including ignored _test.go files)
            InvalidGoFiles    []string // .go source files with detected problems (parse error, wrong package name, and so on)
            IgnoredOtherFiles []string // non-.go source files ignored for this build
            CFiles            []string // .c source files
            CXXFiles          []string // .cc, .cpp and .cxx source files
            MFiles            []string // .m (Objective-C) source files
            HFiles            []string // .h, .hh, .hpp and .hxx source files
            FFiles            []string // .f, .F, .for and .f90 Fortran source files
            SFiles            []string // .s source files
            SwigFiles         []string // .swig files
            SwigCXXFiles      []string // .swigcxx files
            SysoFiles         []string // .syso system object files to add to archive
        
            // Cgo directives
            CgoCFLAGS    []string // Cgo CFLAGS directives
            CgoCPPFLAGS  []string // Cgo CPPFLAGS directives
            CgoCXXFLAGS  []string // Cgo CXXFLAGS directives
            CgoFFLAGS    []string // Cgo FFLAGS directives
            CgoLDFLAGS   []string // Cgo LDFLAGS directives
            CgoPkgConfig []string // Cgo pkg-config directives
        
            // Test information
            TestGoFiles  []string // _test.go files in package
            XTestGoFiles []string // _test.go files outside package
        
            // Go directive comments (//go:zzz...) found in source files.
            Directives      []Directive
            TestDirectives  []Directive
            XTestDirectives []Directive
        
            // Dependency information
            Imports        []string                    // import paths from GoFiles, CgoFiles
            ImportPos      map[string][]token.Position // line information for Imports
            TestImports    []string                    // import paths from TestGoFiles
            TestImportPos  map[string][]token.Position // line information for TestImports
            XTestImports   []string                    // import paths from XTestGoFiles
            XTestImportPos map[string][]token.Position // line information for XTestImports
        
            // //go:embed patterns found in Go source files
            // For example, if a source file says
            //	//go:embed a* b.c
            // then the list will contain those two strings as separate entries.
            // (See package embed for more details about //go:embed.)
            EmbedPatterns        []string                    // patterns from GoFiles, CgoFiles
            EmbedPatternPos      map[string][]token.Position // line information for EmbedPatterns
            TestEmbedPatterns    []string                    // patterns from TestGoFiles
            TestEmbedPatternPos  map[string][]token.Position // line information for TestEmbedPatterns
            XTestEmbedPatterns   []string                    // patterns from XTestGoFiles
            XTestEmbedPatternPos map[string][]token.Position // line information for XTestEmbedPatternPos
        }
        

        func Import

        func Import(path, srcDir string, mode ImportMode) (*Package, error)

        Import is shorthand for Default.Import.

        func ImportDir

        func ImportDir(dir string, mode ImportMode) (*Package, error)

        ImportDir is shorthand for Default.ImportDir.

        func (*Package) IsCommand

        func (p *Package) IsCommand() bool

        IsCommand reports whether the package is considered a command to be installed (not just a library). Packages named "main" are treated as commands.

        Subdirectories

        Name Synopsis
        ..
        constraint Package constraint implements parsing and evaluation of build constraint lines.
        constraint - Go Documentation Server
        ...

        Package constraint

        import "go/build/constraint"
        Overview
        Index

        Overview ▾

        Package constraint implements parsing and evaluation of build constraint lines. See https://golang.org/cmd/go/#hdr-Build_constraints for documentation about build constraints themselves.

        This package parses both the original “// +build” syntax and the “//go:build” syntax that was added in Go 1.17. See https://golang.org/design/draft-gobuild for details about the “//go:build” syntax.

        func GoVersion

        func GoVersion(x Expr) string

        GoVersion returns the minimum Go version implied by a given build expression. If the expression can be satisfied without any Go version tags, GoVersion returns an empty string.

        For example:

        GoVersion(linux && go1.22) = "go1.22"
        GoVersion((linux && go1.22) || (windows && go1.20)) = "go1.20" => go1.20
        GoVersion(linux) = ""
        GoVersion(linux || (windows && go1.22)) = ""
        GoVersion(!go1.22) = ""
        

        GoVersion assumes that any tag or negated tag may independently be true, so that its analysis can be purely structural, without SAT solving. “Impossible” subexpressions may therefore affect the result.

        For example:

        GoVersion((linux && !linux && go1.20) || go1.21) = "go1.20"
        

        func IsGoBuild

        func IsGoBuild(line string) bool

        IsGoBuild reports whether the line of text is a “//go:build” constraint. It only checks the prefix of the text, not that the expression itself parses.

        func IsPlusBuild

        func IsPlusBuild(line string) bool

        IsPlusBuild reports whether the line of text is a “// +build” constraint. It only checks the prefix of the text, not that the expression itself parses.

        func PlusBuildLines

        func PlusBuildLines(x Expr) ([]string, error)

        PlusBuildLines returns a sequence of “// +build” lines that evaluate to the build expression x. If the expression is too complex to convert directly to “// +build” lines, PlusBuildLines returns an error.

        type AndExpr

        An AndExpr represents the expression X && Y.

        type AndExpr struct {
            X, Y Expr
        }
        

        func (*AndExpr) Eval

        func (x *AndExpr) Eval(ok func(tag string) bool) bool

        func (*AndExpr) String

        func (x *AndExpr) String() string

        type Expr

        An Expr is a build tag constraint expression. The underlying concrete type is *AndExpr, *OrExpr, *NotExpr, or *TagExpr.

        type Expr interface {
            // String returns the string form of the expression,
            // using the boolean syntax used in //go:build lines.
            String() string
        
            // Eval reports whether the expression evaluates to true.
            // It calls ok(tag) as needed to find out whether a given build tag
            // is satisfied by the current build configuration.
            Eval(ok func(tag string) bool) bool
            // contains filtered or unexported methods
        }

        func Parse

        func Parse(line string) (Expr, error)

        Parse parses a single build constraint line of the form “//go:build ...” or “// +build ...” and returns the corresponding boolean expression.

        type NotExpr

        A NotExpr represents the expression !X (the negation of X).

        type NotExpr struct {
            X Expr
        }
        

        func (*NotExpr) Eval

        func (x *NotExpr) Eval(ok func(tag string) bool) bool

        func (*NotExpr) String

        func (x *NotExpr) String() string

        type OrExpr

        An OrExpr represents the expression X || Y.

        type OrExpr struct {
            X, Y Expr
        }
        

        func (*OrExpr) Eval

        func (x *OrExpr) Eval(ok func(tag string) bool) bool

        func (*OrExpr) String

        func (x *OrExpr) String() string

        type SyntaxError

        A SyntaxError reports a syntax error in a parsed build expression.

        type SyntaxError struct {
            Offset int    // byte offset in input where error was detected
            Err    string // description of error
        }
        

        func (*SyntaxError) Error

        func (e *SyntaxError) Error() string

        type TagExpr

        A TagExpr is an Expr for the single tag Tag.

        type TagExpr struct {
            Tag string // for example, “linux” or “cgo”
        }
        

        func (*TagExpr) Eval

        func (x *TagExpr) Eval(ok func(tag string) bool) bool

        func (*TagExpr) String

        func (x *TagExpr) String() string
        constant - Go Documentation Server
        ...

        Package constant

        import "go/constant"
        Overview
        Index
        Examples

        Overview ▾

        Package constant implements Values representing untyped Go constants and their corresponding operations.

        A special Unknown value may be used when a value is unknown due to an error. Operations on unknown values produce unknown values unless specified otherwise.

        Example (ComplexNumbers)

        Code:

        // Create the complex number 2.3 + 5i.
        ar := constant.MakeFloat64(2.3)
        ai := constant.MakeImag(constant.MakeInt64(5))
        a := constant.BinaryOp(ar, token.ADD, ai)
        
        // Compute (2.3 + 5i) * 11.
        b := constant.MakeUint64(11)
        c := constant.BinaryOp(a, token.MUL, b)
        
        // Convert c into a complex128.
        Ar, exact := constant.Float64Val(constant.Real(c))
        if !exact {
            fmt.Printf("Could not represent real part %s exactly as float64\n", constant.Real(c))
        }
        Ai, exact := constant.Float64Val(constant.Imag(c))
        if !exact {
            fmt.Printf("Could not represent imaginary part %s as exactly as float64\n", constant.Imag(c))
        }
        C := complex(Ar, Ai)
        
        fmt.Println("literal", 25.3+55i)
        fmt.Println("go/constant", c)
        fmt.Println("complex128", C)
        
        

        Output:

        Could not represent real part 25.3 exactly as float64
        literal (25.3+55i)
        go/constant (25.3 + 55i)
        complex128 (25.299999999999997+55i)
        

        func BitLen

        func BitLen(x Value) int

        BitLen returns the number of bits required to represent the absolute value x in binary representation; x must be an Int or an Unknown. If x is Unknown, the result is 0.

        func BoolVal

        func BoolVal(x Value) bool

        BoolVal returns the Go boolean value of x, which must be a Bool or an Unknown. If x is Unknown, the result is false.

        func Bytes

        func Bytes(x Value) []byte

        Bytes returns the bytes for the absolute value of x in little- endian binary representation; x must be an Int.

        func Compare

        func Compare(x_ Value, op token.Token, y_ Value) bool

        Compare returns the result of the comparison x op y. The comparison must be defined for the operands. If one of the operands is Unknown, the result is false.

        Example

        Code:

        vs := []constant.Value{
            constant.MakeString("Z"),
            constant.MakeString("bacon"),
            constant.MakeString("go"),
            constant.MakeString("Frame"),
            constant.MakeString("defer"),
            constant.MakeFromLiteral(`"a"`, token.STRING, 0),
        }
        
        sort.Slice(vs, func(i, j int) bool {
            // Equivalent to vs[i] <= vs[j].
            return constant.Compare(vs[i], token.LEQ, vs[j])
        })
        
        for _, v := range vs {
            fmt.Println(constant.StringVal(v))
        }
        
        

        Output:

        Frame
        Z
        a
        bacon
        defer
        go
        

        func Float32Val

        func Float32Val(x Value) (float32, bool)

        Float32Val is like Float64Val but for float32 instead of float64.

        func Float64Val

        func Float64Val(x Value) (float64, bool)

        Float64Val returns the nearest Go float64 value of x and whether the result is exact; x must be numeric or an Unknown, but not Complex. For values too small (too close to 0) to represent as float64, Float64Val silently underflows to 0. The result sign always matches the sign of x, even for 0. If x is Unknown, the result is (0, false).

        func Int64Val

        func Int64Val(x Value) (int64, bool)

        Int64Val returns the Go int64 value of x and whether the result is exact; x must be an Int or an Unknown. If the result is not exact, its value is undefined. If x is Unknown, the result is (0, false).

        func Sign

        func Sign(x Value) int

        Sign returns -1, 0, or 1 depending on whether x < 0, x == 0, or x > 0; x must be numeric or Unknown. For complex values x, the sign is 0 if x == 0, otherwise it is != 0. If x is Unknown, the result is 1.

        Example

        Code:

        zero := constant.MakeInt64(0)
        one := constant.MakeInt64(1)
        negOne := constant.MakeInt64(-1)
        
        mkComplex := func(a, b constant.Value) constant.Value {
            b = constant.MakeImag(b)
            return constant.BinaryOp(a, token.ADD, b)
        }
        
        vs := []constant.Value{
            negOne,
            mkComplex(zero, negOne),
            mkComplex(one, negOne),
            mkComplex(negOne, one),
            mkComplex(negOne, negOne),
            zero,
            mkComplex(zero, zero),
            one,
            mkComplex(zero, one),
            mkComplex(one, one),
        }
        
        for _, v := range vs {
            fmt.Printf("% d %s\n", constant.Sign(v), v)
        }
        
        

        Output:

        -1 -1
        -1 (0 + -1i)
        -1 (1 + -1i)
        -1 (-1 + 1i)
        -1 (-1 + -1i)
         0 0
         0 (0 + 0i)
         1 1
         1 (0 + 1i)
         1 (1 + 1i)
        

        func StringVal

        func StringVal(x Value) string

        StringVal returns the Go string value of x, which must be a String or an Unknown. If x is Unknown, the result is "".

        func Uint64Val

        func Uint64Val(x Value) (uint64, bool)

        Uint64Val returns the Go uint64 value of x and whether the result is exact; x must be an Int or an Unknown. If the result is not exact, its value is undefined. If x is Unknown, the result is (0, false).

        func Val

        func Val(x Value) any

        Val returns the underlying value for a given constant. Since it returns an interface, it is up to the caller to type assert the result to the expected type. The possible dynamic return types are:

        x Kind             type of result
        -----------------------------------------
        Bool               bool
        String             string
        Int                int64 or *big.Int
        Float              *big.Float or *big.Rat
        everything else    nil
        

        Example

        Code:

        maxint := constant.MakeInt64(math.MaxInt64)
        fmt.Printf("%v\n", constant.Val(maxint))
        
        e := constant.MakeFloat64(math.E)
        fmt.Printf("%v\n", constant.Val(e))
        
        b := constant.MakeBool(true)
        fmt.Printf("%v\n", constant.Val(b))
        
        b = constant.Make(false)
        fmt.Printf("%v\n", constant.Val(b))
        
        

        Output:

        9223372036854775807
        6121026514868073/2251799813685248
        true
        false
        

        type Kind

        Kind specifies the kind of value represented by a Value.

        type Kind int
        const (
            // unknown values
            Unknown Kind = iota
        
            // non-numeric values
            Bool
            String
        
            // numeric values
            Int
            Float
            Complex
        )

        func (Kind) String

        func (i Kind) String() string

        type Value

        A Value represents the value of a Go constant.

        type Value interface {
            // Kind returns the value kind.
            Kind() Kind
        
            // String returns a short, quoted (human-readable) form of the value.
            // For numeric values, the result may be an approximation;
            // for String values the result may be a shortened string.
            // Use ExactString for a string representing a value exactly.
            String() string
        
            // ExactString returns an exact, quoted (human-readable) form of the value.
            // If the Value is of Kind String, use StringVal to obtain the unquoted string.
            ExactString() string
            // contains filtered or unexported methods
        }

        func BinaryOp

        func BinaryOp(x_ Value, op token.Token, y_ Value) Value

        BinaryOp returns the result of the binary expression x op y. The operation must be defined for the operands. If one of the operands is Unknown, the result is Unknown. BinaryOp doesn't handle comparisons or shifts; use Compare or Shift instead.

        To force integer division of Int operands, use op == token.QUO_ASSIGN instead of token.QUO; the result is guaranteed to be Int in this case. Division by zero leads to a run-time panic.

        Example

        Code:

        // 11 / 0.5
        a := constant.MakeUint64(11)
        b := constant.MakeFloat64(0.5)
        c := constant.BinaryOp(a, token.QUO, b)
        fmt.Println(c)
        
        

        Output:

        22
        

        func Denom

        func Denom(x Value) Value

        Denom returns the denominator of x; x must be Int, Float, or Unknown. If x is Unknown, or if it is too large or small to represent as a fraction, the result is Unknown. Otherwise the result is an Int >= 1.

        func Imag

        func Imag(x Value) Value

        Imag returns the imaginary part of x, which must be a numeric or unknown value. If x is Unknown, the result is Unknown.

        func Make

        func Make(x any) Value

        Make returns the Value for x.

        type of x        result Kind
        ----------------------------
        bool             Bool
        string           String
        int64            Int
        *big.Int         Int
        *big.Float       Float
        *big.Rat         Float
        anything else    Unknown
        

        func MakeBool

        func MakeBool(b bool) Value

        MakeBool returns the Bool value for b.

        func MakeFloat64

        func MakeFloat64(x float64) Value

        MakeFloat64 returns the Float value for x. If x is -0.0, the result is 0.0. If x is not finite, the result is an Unknown.

        func MakeFromBytes

        func MakeFromBytes(bytes []byte) Value

        MakeFromBytes returns the Int value given the bytes of its little-endian binary representation. An empty byte slice argument represents 0.

        func MakeFromLiteral

        func MakeFromLiteral(lit string, tok token.Token, zero uint) Value

        MakeFromLiteral returns the corresponding integer, floating-point, imaginary, character, or string value for a Go literal string. The tok value must be one of token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING. The final argument must be zero. If the literal string syntax is invalid, the result is an Unknown.

        func MakeImag

        func MakeImag(x Value) Value

        MakeImag returns the Complex value x*i; x must be Int, Float, or Unknown. If x is Unknown, the result is Unknown.

        func MakeInt64

        func MakeInt64(x int64) Value

        MakeInt64 returns the Int value for x.

        func MakeString

        func MakeString(s string) Value

        MakeString returns the String value for s.

        func MakeUint64

        func MakeUint64(x uint64) Value

        MakeUint64 returns the Int value for x.

        func MakeUnknown

        func MakeUnknown() Value

        MakeUnknown returns the Unknown value.

        func Num

        func Num(x Value) Value

        Num returns the numerator of x; x must be Int, Float, or Unknown. If x is Unknown, or if it is too large or small to represent as a fraction, the result is Unknown. Otherwise the result is an Int with the same sign as x.

        func Real

        func Real(x Value) Value

        Real returns the real part of x, which must be a numeric or unknown value. If x is Unknown, the result is Unknown.

        func Shift

        func Shift(x Value, op token.Token, s uint) Value

        Shift returns the result of the shift expression x op s with op == token.SHL or token.SHR (<< or >>). x must be an Int or an Unknown. If x is Unknown, the result is x.

        func ToComplex

        func ToComplex(x Value) Value

        ToComplex converts x to a Complex value if x is representable as a Complex. Otherwise it returns an Unknown.

        func ToFloat

        func ToFloat(x Value) Value

        ToFloat converts x to a Float value if x is representable as a Float. Otherwise it returns an Unknown.

        func ToInt

        func ToInt(x Value) Value

        ToInt converts x to an Int value if x is representable as an Int. Otherwise it returns an Unknown.

        func UnaryOp

        func UnaryOp(op token.Token, y Value, prec uint) Value

        UnaryOp returns the result of the unary expression op y. The operation must be defined for the operand. If prec > 0 it specifies the ^ (xor) result size in bits. If y is Unknown, the result is Unknown.

        Example

        Code:

        vs := []constant.Value{
            constant.MakeBool(true),
            constant.MakeFloat64(2.7),
            constant.MakeUint64(42),
        }
        
        for i, v := range vs {
            switch v.Kind() {
            case constant.Bool:
                vs[i] = constant.UnaryOp(token.NOT, v, 0)
        
            case constant.Float:
                vs[i] = constant.UnaryOp(token.SUB, v, 0)
        
            case constant.Int:
                // Use 16-bit precision.
                // This would be equivalent to ^uint16(v).
                vs[i] = constant.UnaryOp(token.XOR, v, 16)
            }
        }
        
        for _, v := range vs {
            fmt.Println(v)
        }
        
        

        Output:

        false
        -2.7
        65493
        
        doc - Go Documentation Server
        ...

        Package doc

        Overview ▾

        Package doc extracts source code documentation from a Go AST.

        Variables

        IllegalPrefixes is a list of lower-case prefixes that identify a comment as not being a doc comment. This helps to avoid misinterpreting the common mistake of a copyright notice immediately before a package statement as being a doc comment.

        var IllegalPrefixes = []string{
            "copyright",
            "all rights",
            "author",
        }

        func IsPredeclared

        func IsPredeclared(s string) bool

        IsPredeclared reports whether s is a predeclared identifier.

        func Synopsis

        func Synopsis(text string) string

        Synopsis returns a cleaned version of the first sentence in text.

        Deprecated: New programs should use Package.Synopsis instead, which handles links in text properly.

        func ToHTML

        func ToHTML(w io.Writer, text string, words map[string]string)

        ToHTML converts comment text to formatted HTML.

        Deprecated: ToHTML cannot identify documentation links in the doc comment, because they depend on knowing what package the text came from, which is not included in this API.

        Given the *doc.Package p where text was found, ToHTML(w, text, nil) can be replaced by:

        w.Write(p.HTML(text))
        

        which is in turn shorthand for:

        w.Write(p.Printer().HTML(p.Parser().Parse(text)))
        

        If words may be non-nil, the longer replacement is:

        parser := p.Parser()
        parser.Words = words
        w.Write(p.Printer().HTML(parser.Parse(d)))
        

        func ToText

        func ToText(w io.Writer, text string, prefix, codePrefix string, width int)

        ToText converts comment text to formatted text.

        Deprecated: ToText cannot identify documentation links in the doc comment, because they depend on knowing what package the text came from, which is not included in this API.

        Given the *doc.Package p where text was found, ToText(w, text, "", "\t", 80) can be replaced by:

        w.Write(p.Text(text))
        

        In the general case, ToText(w, text, prefix, codePrefix, width) can be replaced by:

        d := p.Parser().Parse(text)
        pr := p.Printer()
        pr.TextPrefix = prefix
        pr.TextCodePrefix = codePrefix
        pr.TextWidth = width
        w.Write(pr.Text(d))
        

        See the documentation for Package.Text and comment.Printer.Text for more details.

        type Example

        An Example represents an example function found in a test source file.

        type Example struct {
            Name        string // name of the item being exemplified (including optional suffix)
            Suffix      string // example suffix, without leading '_' (only populated by NewFromFiles)
            Doc         string // example function doc string
            Code        ast.Node
            Play        *ast.File // a whole program version of the example
            Comments    []*ast.CommentGroup
            Output      string // expected output
            Unordered   bool
            EmptyOutput bool // expect empty output
            Order       int  // original source code order
        }
        

        func Examples

        func Examples(testFiles ...*ast.File) []*Example

        Examples returns the examples found in testFiles, sorted by Name field. The Order fields record the order in which the examples were encountered. The Suffix field is not populated when Examples is called directly, it is only populated by NewFromFiles for examples it finds in _test.go files.

        Playable Examples must be in a package whose name ends in "_test". An Example is "playable" (the Play field is non-nil) in either of these circumstances:

        • The example function is self-contained: the function references only identifiers from other packages (or predeclared identifiers, such as "int") and the test file does not include a dot import.
        • The entire test file is the example: the file contains exactly one example function, zero test, fuzz test, or benchmark function, and at least one top-level function, type, variable, or constant declaration other than the example function.

        type Filter

        type Filter func(string) bool

        type Func

        Func is the documentation for a func declaration.

        type Func struct {
            Doc  string
            Name string
            Decl *ast.FuncDecl
        
            // methods
            // (for functions, these fields have the respective zero value)
            Recv  string // actual   receiver "T" or "*T" possibly followed by type parameters [P1, ..., Pn]
            Orig  string // original receiver "T" or "*T"
            Level int    // embedding level; 0 means not embedded
        
            // Examples is a sorted list of examples associated with this
            // function or method. Examples are extracted from _test.go files
            // provided to NewFromFiles.
            Examples []*Example
        }
        

        type Mode

        Mode values control the operation of New and NewFromFiles.

        type Mode int
        const (
            // AllDecls says to extract documentation for all package-level
            // declarations, not just exported ones.
            AllDecls Mode = 1 << iota
        
            // AllMethods says to show all embedded methods, not just the ones of
            // invisible (unexported) anonymous fields.
            AllMethods
        
            // PreserveAST says to leave the AST unmodified. Originally, pieces of
            // the AST such as function bodies were nil-ed out to save memory in
            // godoc, but not all programs want that behavior.
            PreserveAST
        )

        type Note

        A Note represents a marked comment starting with "MARKER(uid): note body". Any note with a marker of 2 or more upper case [A-Z] letters and a uid of at least one character is recognized. The ":" following the uid is optional. Notes are collected in the Package.Notes map indexed by the notes marker.

        type Note struct {
            Pos, End token.Pos // position range of the comment containing the marker
            UID      string    // uid found with the marker
            Body     string    // note body text
        }
        

        type Package

        Package is the documentation for an entire package.

        type Package struct {
            Doc        string
            Name       string
            ImportPath string
            Imports    []string
            Filenames  []string
            Notes      map[string][]*Note
        
            // Deprecated: For backward compatibility Bugs is still populated,
            // but all new code should use Notes instead.
            Bugs []string
        
            // declarations
            Consts []*Value
            Types  []*Type
            Vars   []*Value
            Funcs  []*Func
        
            // Examples is a sorted list of examples associated with
            // the package. Examples are extracted from _test.go files
            // provided to NewFromFiles.
            Examples []*Example
            // contains filtered or unexported fields
        }
        

        func New

        func New(pkg *ast.Package, importPath string, mode Mode) *Package

        New computes the package documentation for the given package AST. New takes ownership of the AST pkg and may edit or overwrite it. To have the Examples fields populated, use NewFromFiles and include the package's _test.go files.

        func NewFromFiles

        func NewFromFiles(fset *token.FileSet, files []*ast.File, importPath string, opts ...any) (*Package, error)

        NewFromFiles computes documentation for a package.

        The package is specified by a list of *ast.Files and corresponding file set, which must not be nil. NewFromFiles uses all provided files when computing documentation, so it is the caller's responsibility to provide only the files that match the desired build context. "go/build".Context.MatchFile can be used for determining whether a file matches a build context with the desired GOOS and GOARCH values, and other build constraints. The import path of the package is specified by importPath.

        Examples found in _test.go files are associated with the corresponding type, function, method, or the package, based on their name. If the example has a suffix in its name, it is set in the [Example.Suffix] field. Examples with malformed names are skipped.

        Optionally, a single extra argument of type Mode can be provided to control low-level aspects of the documentation extraction behavior.

        NewFromFiles takes ownership of the AST files and may edit them, unless the PreserveAST Mode bit is on.

        Example

        This example illustrates how to use NewFromFiles to compute package documentation with examples.

        Code:

        // src and test are two source files that make up
        // a package whose documentation will be computed.
        const src = `
        // This is the package comment.
        package p
        
        import "fmt"
        
        // This comment is associated with the Greet function.
        func Greet(who string) {
            fmt.Printf("Hello, %s!\n", who)
        }
        `
        const test = `
        package p_test
        
        // This comment is associated with the ExampleGreet_world example.
        func ExampleGreet_world() {
            Greet("world")
        }
        `
        
        // Create the AST by parsing src and test.
        fset := token.NewFileSet()
        files := []*ast.File{
            mustParse(fset, "src.go", src),
            mustParse(fset, "src_test.go", test),
        }
        
        // Compute package documentation with examples.
        p, err := doc.NewFromFiles(fset, files, "example.com/p")
        if err != nil {
            panic(err)
        }
        
        fmt.Printf("package %s - %s", p.Name, p.Doc)
        fmt.Printf("func %s - %s", p.Funcs[0].Name, p.Funcs[0].Doc)
        fmt.Printf(" ⤷ example with suffix %q - %s", p.Funcs[0].Examples[0].Suffix, p.Funcs[0].Examples[0].Doc)
        
        

        Output:

        package p - This is the package comment.
        func Greet - This comment is associated with the Greet function.
         ⤷ example with suffix "world" - This comment is associated with the ExampleGreet_world example.
        

        func (*Package) Filter

        func (p *Package) Filter(f Filter)

        Filter eliminates documentation for names that don't pass through the filter f. TODO(gri): Recognize "Type.Method" as a name.

        func (*Package) HTML

        func (p *Package) HTML(text string) []byte

        HTML returns formatted HTML for the doc comment text.

        To customize details of the HTML, use Package.Printer to obtain a comment.Printer, and configure it before calling its HTML method.

        func (*Package) Markdown

        func (p *Package) Markdown(text string) []byte

        Markdown returns formatted Markdown for the doc comment text.

        To customize details of the Markdown, use Package.Printer to obtain a comment.Printer, and configure it before calling its Markdown method.

        func (*Package) Parser

        func (p *Package) Parser() *comment.Parser

        Parser returns a doc comment parser configured for parsing doc comments from package p. Each call returns a new parser, so that the caller may customize it before use.

        func (*Package) Printer

        func (p *Package) Printer() *comment.Printer

        Printer returns a doc comment printer configured for printing doc comments from package p. Each call returns a new printer, so that the caller may customize it before use.

        func (*Package) Synopsis

        func (p *Package) Synopsis(text string) string

        Synopsis returns a cleaned version of the first sentence in text. That sentence ends after the first period followed by space and not preceded by exactly one uppercase letter, or at the first paragraph break. The result string has no \n, \r, or \t characters and uses only single spaces between words. If text starts with any of the IllegalPrefixes, the result is the empty string.

        func (*Package) Text

        func (p *Package) Text(text string) []byte

        Text returns formatted text for the doc comment text, wrapped to 80 Unicode code points and using tabs for code block indentation.

        To customize details of the formatting, use Package.Printer to obtain a comment.Printer, and configure it before calling its Text method.

        type Type

        Type is the documentation for a type declaration.

        type Type struct {
            Doc  string
            Name string
            Decl *ast.GenDecl
        
            // associated declarations
            Consts  []*Value // sorted list of constants of (mostly) this type
            Vars    []*Value // sorted list of variables of (mostly) this type
            Funcs   []*Func  // sorted list of functions returning this type
            Methods []*Func  // sorted list of methods (including embedded ones) of this type
        
            // Examples is a sorted list of examples associated with
            // this type. Examples are extracted from _test.go files
            // provided to NewFromFiles.
            Examples []*Example
        }
        

        type Value

        Value is the documentation for a (possibly grouped) var or const declaration.

        type Value struct {
            Doc   string
            Names []string // var or const names in declaration order
            Decl  *ast.GenDecl
            // contains filtered or unexported fields
        }
        

        Subdirectories

        Name Synopsis
        ..
        comment Package comment implements parsing and reformatting of Go doc comments, (documentation comments), which are comments that immediately precede a top-level declaration of a package, const, func, type, or var.
        comment - Go Documentation Server
        ...

        Package comment

        import "go/doc/comment"
        Overview
        Index

        Overview ▾

        Package comment implements parsing and reformatting of Go doc comments, (documentation comments), which are comments that immediately precede a top-level declaration of a package, const, func, type, or var.

        Go doc comment syntax is a simplified subset of Markdown that supports links, headings, paragraphs, lists (without nesting), and preformatted text blocks. The details of the syntax are documented at https://go.dev/doc/comment.

        To parse the text associated with a doc comment (after removing comment markers), use a Parser:

        var p comment.Parser
        doc := p.Parse(text)
        

        The result is a *Doc. To reformat it as a doc comment, HTML, Markdown, or plain text, use a Printer:

        var pr comment.Printer
        os.Stdout.Write(pr.Text(doc))
        

        The Parser and Printer types are structs whose fields can be modified to customize the operations. For details, see the documentation for those types.

        Use cases that need additional control over reformatting can implement their own logic by inspecting the parsed syntax itself. See the documentation for Doc, Block, Text for an overview and links to additional types.

        func DefaultLookupPackage

        func DefaultLookupPackage(name string) (importPath string, ok bool)

        DefaultLookupPackage is the default package lookup function, used when [Parser.LookupPackage] is nil. It recognizes names of the packages from the standard library with single-element import paths, such as math, which would otherwise be impossible to name.

        Note that the go/doc package provides a more sophisticated lookup based on the imports used in the current package.

        type Block

        A Block is block-level content in a doc comment, one of *Code, *Heading, *List, or *Paragraph.

        type Block interface {
            // contains filtered or unexported methods
        }

        type Code

        A Code is a preformatted code block.

        type Code struct {
            // Text is the preformatted text, ending with a newline character.
            // It may be multiple lines, each of which ends with a newline character.
            // It is never empty, nor does it start or end with a blank line.
            Text string
        }
        

        type Doc

        A Doc is a parsed Go doc comment.

        type Doc struct {
            // Content is the sequence of content blocks in the comment.
            Content []Block
        
            // Links is the link definitions in the comment.
            Links []*LinkDef
        }
        

        A DocLink is a link to documentation for a Go package or symbol.

        type DocLink struct {
            Text []Text // text of link
        
            // ImportPath, Recv, and Name identify the Go package or symbol
            // that is the link target. The potential combinations of
            // non-empty fields are:
            //  - ImportPath: a link to another package
            //  - ImportPath, Name: a link to a const, func, type, or var in another package
            //  - ImportPath, Recv, Name: a link to a method in another package
            //  - Name: a link to a const, func, type, or var in this package
            //  - Recv, Name: a link to a method in this package
            ImportPath string // import path
            Recv       string // receiver type, without any pointer star, for methods
            Name       string // const, func, type, var, or method name
        }
        

        func (*DocLink) DefaultURL

        func (l *DocLink) DefaultURL(baseURL string) string

        DefaultURL constructs and returns the documentation URL for l, using baseURL as a prefix for links to other packages.

        The possible forms returned by DefaultURL are:

        • baseURL/ImportPath, for a link to another package
        • baseURL/ImportPath#Name, for a link to a const, func, type, or var in another package
        • baseURL/ImportPath#Recv.Name, for a link to a method in another package
        • #Name, for a link to a const, func, type, or var in this package
        • #Recv.Name, for a link to a method in this package

        If baseURL ends in a trailing slash, then DefaultURL inserts a slash between ImportPath and # in the anchored forms. For example, here are some baseURL values and URLs they can generate:

        "/pkg/" → "/pkg/math/#Sqrt"
        "/pkg"  → "/pkg/math#Sqrt"
        "/"     → "/math/#Sqrt"
        ""      → "/math#Sqrt"
        

        type Heading

        A Heading is a doc comment heading.

        type Heading struct {
            Text []Text // the heading text
        }
        

        func (*Heading) DefaultID

        func (h *Heading) DefaultID() string

        DefaultID returns the default anchor ID for the heading h.

        The default anchor ID is constructed by converting every rune that is not alphanumeric ASCII to an underscore and then adding the prefix “hdr-”. For example, if the heading text is “Go Doc Comments”, the default ID is “hdr-Go_Doc_Comments”.

        type Italic

        An Italic is a string rendered as italicized text.

        type Italic string

        A Link is a link to a specific URL.

        type Link struct {
            Auto bool   // is this an automatic (implicit) link of a literal URL?
            Text []Text // text of link
            URL  string // target URL of link
        }
        

        type LinkDef

        A LinkDef is a single link definition.

        type LinkDef struct {
            Text string // the link text
            URL  string // the link URL
            Used bool   // whether the comment uses the definition
        }
        

        type List

        A List is a numbered or bullet list. Lists are always non-empty: len(Items) > 0. In a numbered list, every Items[i].Number is a non-empty string. In a bullet list, every Items[i].Number is an empty string.

        type List struct {
            // Items is the list items.
            Items []*ListItem
        
            // ForceBlankBefore indicates that the list must be
            // preceded by a blank line when reformatting the comment,
            // overriding the usual conditions. See the BlankBefore method.
            //
            // The comment parser sets ForceBlankBefore for any list
            // that is preceded by a blank line, to make sure
            // the blank line is preserved when printing.
            ForceBlankBefore bool
        
            // ForceBlankBetween indicates that list items must be
            // separated by blank lines when reformatting the comment,
            // overriding the usual conditions. See the BlankBetween method.
            //
            // The comment parser sets ForceBlankBetween for any list
            // that has a blank line between any two of its items, to make sure
            // the blank lines are preserved when printing.
            ForceBlankBetween bool
        }
        

        func (*List) BlankBefore

        func (l *List) BlankBefore() bool

        BlankBefore reports whether a reformatting of the comment should include a blank line before the list. The default rule is the same as for [BlankBetween]: if the list item content contains any blank lines (meaning at least one item has multiple paragraphs) then the list itself must be preceded by a blank line. A preceding blank line can be forced by setting List.ForceBlankBefore.

        func (*List) BlankBetween

        func (l *List) BlankBetween() bool

        BlankBetween reports whether a reformatting of the comment should include a blank line between each pair of list items. The default rule is that if the list item content contains any blank lines (meaning at least one item has multiple paragraphs) then list items must themselves be separated by blank lines. Blank line separators can be forced by setting List.ForceBlankBetween.

        type ListItem

        A ListItem is a single item in a numbered or bullet list.

        type ListItem struct {
            // Number is a decimal string in a numbered list
            // or an empty string in a bullet list.
            Number string // "1", "2", ...; "" for bullet list
        
            // Content is the list content.
            // Currently, restrictions in the parser and printer
            // require every element of Content to be a *Paragraph.
            Content []Block // Content of this item.
        }
        

        type Paragraph

        A Paragraph is a paragraph of text.

        type Paragraph struct {
            Text []Text
        }
        

        type Parser

        A Parser is a doc comment parser. The fields in the struct can be filled in before calling Parser.Parse in order to customize the details of the parsing process.

        type Parser struct {
            // Words is a map of Go identifier words that
            // should be italicized and potentially linked.
            // If Words[w] is the empty string, then the word w
            // is only italicized. Otherwise it is linked, using
            // Words[w] as the link target.
            // Words corresponds to the [go/doc.ToHTML] words parameter.
            Words map[string]string
        
            // LookupPackage resolves a package name to an import path.
            //
            // If LookupPackage(name) returns ok == true, then [name]
            // (or [name.Sym] or [name.Sym.Method])
            // is considered a documentation link to importPath's package docs.
            // It is valid to return "", true, in which case name is considered
            // to refer to the current package.
            //
            // If LookupPackage(name) returns ok == false,
            // then [name] (or [name.Sym] or [name.Sym.Method])
            // will not be considered a documentation link,
            // except in the case where name is the full (but single-element) import path
            // of a package in the standard library, such as in [math] or [io.Reader].
            // LookupPackage is still called for such names,
            // in order to permit references to imports of other packages
            // with the same package names.
            //
            // Setting LookupPackage to nil is equivalent to setting it to
            // a function that always returns "", false.
            LookupPackage func(name string) (importPath string, ok bool)
        
            // LookupSym reports whether a symbol name or method name
            // exists in the current package.
            //
            // If LookupSym("", "Name") returns true, then [Name]
            // is considered a documentation link for a const, func, type, or var.
            //
            // Similarly, if LookupSym("Recv", "Name") returns true,
            // then [Recv.Name] is considered a documentation link for
            // type Recv's method Name.
            //
            // Setting LookupSym to nil is equivalent to setting it to a function
            // that always returns false.
            LookupSym func(recv, name string) (ok bool)
        }
        

        func (*Parser) Parse

        func (p *Parser) Parse(text string) *Doc

        Parse parses the doc comment text and returns the *Doc form. Comment markers (/* // and */) in the text must have already been removed.

        type Plain

        A Plain is a string rendered as plain text (not italicized).

        type Plain string

        type Printer

        A Printer is a doc comment printer. The fields in the struct can be filled in before calling any of the printing methods in order to customize the details of the printing process.

        type Printer struct {
            // HeadingLevel is the nesting level used for
            // HTML and Markdown headings.
            // If HeadingLevel is zero, it defaults to level 3,
            // meaning to use <h3> and ###.
            HeadingLevel int
        
            // HeadingID is a function that computes the heading ID
            // (anchor tag) to use for the heading h when generating
            // HTML and Markdown. If HeadingID returns an empty string,
            // then the heading ID is omitted.
            // If HeadingID is nil, h.DefaultID is used.
            HeadingID func(h *Heading) string
        
            // DocLinkURL is a function that computes the URL for the given DocLink.
            // If DocLinkURL is nil, then link.DefaultURL(p.DocLinkBaseURL) is used.
            DocLinkURL func(link *DocLink) string
        
            // DocLinkBaseURL is used when DocLinkURL is nil,
            // passed to [DocLink.DefaultURL] to construct a DocLink's URL.
            // See that method's documentation for details.
            DocLinkBaseURL string
        
            // TextPrefix is a prefix to print at the start of every line
            // when generating text output using the Text method.
            TextPrefix string
        
            // TextCodePrefix is the prefix to print at the start of each
            // preformatted (code block) line when generating text output,
            // instead of (not in addition to) TextPrefix.
            // If TextCodePrefix is the empty string, it defaults to TextPrefix+"\t".
            TextCodePrefix string
        
            // TextWidth is the maximum width text line to generate,
            // measured in Unicode code points,
            // excluding TextPrefix and the newline character.
            // If TextWidth is zero, it defaults to 80 minus the number of code points in TextPrefix.
            // If TextWidth is negative, there is no limit.
            TextWidth int
        }
        

        func (*Printer) Comment

        func (p *Printer) Comment(d *Doc) []byte

        Comment returns the standard Go formatting of the Doc, without any comment markers.

        func (*Printer) HTML

        func (p *Printer) HTML(d *Doc) []byte

        HTML returns an HTML formatting of the Doc. See the Printer documentation for ways to customize the HTML output.

        func (*Printer) Markdown

        func (p *Printer) Markdown(d *Doc) []byte

        Markdown returns a Markdown formatting of the Doc. See the Printer documentation for ways to customize the Markdown output.

        func (*Printer) Text

        func (p *Printer) Text(d *Doc) []byte

        Text returns a textual formatting of the Doc. See the Printer documentation for ways to customize the text output.

        type Text

        A Text is text-level content in a doc comment, one of Plain, Italic, *Link, or *DocLink.

        type Text interface {
            // contains filtered or unexported methods
        }
        format - Go Documentation Server
        ...

        Package format

        import "go/format"
        Overview
        Index
        Examples

        Overview ▾

        Package format implements standard formatting of Go source.

        Note that formatting of Go source code changes over time, so tools relying on consistent formatting should execute a specific version of the gofmt binary instead of using this package. That way, the formatting will be stable, and the tools won't need to be recompiled each time gofmt changes.

        For example, pre-submit checks that use this package directly would behave differently depending on what Go version each developer uses, causing the check to be inherently fragile.

        func Node

        func Node(dst io.Writer, fset *token.FileSet, node any) error

        Node formats node in canonical gofmt style and writes the result to dst.

        The node type must be *ast.File, *printer.CommentedNode, []ast.Decl, []ast.Stmt, or assignment-compatible to ast.Expr, ast.Decl, ast.Spec, or ast.Stmt. Node does not modify node. Imports are not sorted for nodes representing partial source files (for instance, if the node is not an *ast.File or a *printer.CommentedNode not wrapping an *ast.File).

        The function may return early (before the entire result is written) and return a formatting error, for instance due to an incorrect AST.

        Example

        Code:

        const expr = "(6+2*3)/4"
        
        // parser.ParseExpr parses the argument and returns the
        // corresponding ast.Node.
        node, err := parser.ParseExpr(expr)
        if err != nil {
            log.Fatal(err)
        }
        
        // Create a FileSet for node. Since the node does not come
        // from a real source file, fset will be empty.
        fset := token.NewFileSet()
        
        var buf bytes.Buffer
        err = format.Node(&buf, fset, node)
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Println(buf.String())
        
        

        Output:

        (6 + 2*3) / 4
        

        func Source

        func Source(src []byte) ([]byte, error)

        Source formats src in canonical gofmt style and returns the result or an (I/O or syntax) error. src is expected to be a syntactically correct Go source file, or a list of Go declarations or statements.

        If src is a partial source file, the leading and trailing space of src is applied to the result (such that it has the same leading and trailing space as src), and the result is indented by the same amount as the first line of src containing code. Imports are not sorted for partial source files.

        importer - Go Documentation Server
        ...

        Package importer

        import "go/importer"
        Overview
        Index

        Overview ▾

        Package importer provides access to export data importers.

        func Default

        func Default() types.Importer

        Default returns an Importer for the compiler that built the running binary. If available, the result implements types.ImporterFrom.

        func For

        func For(compiler string, lookup Lookup) types.Importer

        For calls ForCompiler with a new FileSet.

        Deprecated: Use ForCompiler, which populates a FileSet with the positions of objects created by the importer.

        func ForCompiler

        func ForCompiler(fset *token.FileSet, compiler string, lookup Lookup) types.Importer

        ForCompiler returns an Importer for importing from installed packages for the compilers "gc" and "gccgo", or for importing directly from the source if the compiler argument is "source". In this latter case, importing may fail under circumstances where the exported API is not entirely defined in pure Go source code (if the package API depends on cgo-defined entities, the type checker won't have access to those).

        The lookup function is called each time the resulting importer needs to resolve an import path. In this mode the importer can only be invoked with canonical import paths (not relative or absolute ones); it is assumed that the translation to canonical import paths is being done by the client of the importer.

        A lookup function must be provided for correct module-aware operation. Deprecated: If lookup is nil, for backwards-compatibility, the importer will attempt to resolve imports in the $GOPATH workspace.

        type Lookup

        A Lookup function returns a reader to access package data for a given import path, or an error if no matching package is found.

        type Lookup func(path string) (io.ReadCloser, error)
        parser - Go Documentation Server
        ...

        Package parser

        import "go/parser"
        Overview
        Index
        Examples

        Overview ▾

        Package parser implements a parser for Go source files. Input may be provided in a variety of forms (see the various Parse* functions); the output is an abstract syntax tree (AST) representing the Go source. The parser is invoked through one of the Parse* functions.

        The parser accepts a larger language than is syntactically permitted by the Go spec, for simplicity, and for improved robustness in the presence of syntax errors. For instance, in method declarations, the receiver is treated like an ordinary parameter list and thus may contain multiple entries where the spec permits exactly one. Consequently, the corresponding field in the AST (ast.FuncDecl.Recv) field is not restricted to one entry.

        func ParseDir

        func ParseDir(fset *token.FileSet, path string, filter func(fs.FileInfo) bool, mode Mode) (pkgs map[string]*ast.Package, first error)

        ParseDir calls ParseFile for all files with names ending in ".go" in the directory specified by path and returns a map of package name -> package AST with all the packages found.

        If filter != nil, only the files with fs.FileInfo entries passing through the filter (and ending in ".go") are considered. The mode bits are passed to ParseFile unchanged. Position information is recorded in fset, which must not be nil.

        If the directory couldn't be read, a nil map and the respective error are returned. If a parse error occurred, a non-nil but incomplete map and the first error encountered are returned.

        func ParseExpr

        func ParseExpr(x string) (ast.Expr, error)

        ParseExpr is a convenience function for obtaining the AST of an expression x. The position information recorded in the AST is undefined. The filename used in error messages is the empty string.

        If syntax errors were found, the result is a partial AST (with ast.Bad* nodes representing the fragments of erroneous source code). Multiple errors are returned via a scanner.ErrorList which is sorted by source position.

        func ParseExprFrom

        func ParseExprFrom(fset *token.FileSet, filename string, src any, mode Mode) (expr ast.Expr, err error)

        ParseExprFrom is a convenience function for parsing an expression. The arguments have the same meaning as for ParseFile, but the source must be a valid Go (type or value) expression. Specifically, fset must not be nil.

        If the source couldn't be read, the returned AST is nil and the error indicates the specific failure. If the source was read but syntax errors were found, the result is a partial AST (with ast.Bad* nodes representing the fragments of erroneous source code). Multiple errors are returned via a scanner.ErrorList which is sorted by source position.

        func ParseFile

        func ParseFile(fset *token.FileSet, filename string, src any, mode Mode) (f *ast.File, err error)

        ParseFile parses the source code of a single Go source file and returns the corresponding ast.File node. The source code may be provided via the filename of the source file, or via the src parameter.

        If src != nil, ParseFile parses the source from src and the filename is only used when recording position information. The type of the argument for the src parameter must be string, []byte, or io.Reader. If src == nil, ParseFile parses the file specified by filename.

        The mode parameter controls the amount of source text parsed and other optional parser functionality. If the SkipObjectResolution mode bit is set (recommended), the object resolution phase of parsing will be skipped, causing File.Scope, File.Unresolved, and all Ident.Obj fields to be nil. Those fields are deprecated; see ast.Object for details.

        Position information is recorded in the file set fset, which must not be nil.

        If the source couldn't be read, the returned AST is nil and the error indicates the specific failure. If the source was read but syntax errors were found, the result is a partial AST (with ast.Bad* nodes representing the fragments of erroneous source code). Multiple errors are returned via a scanner.ErrorList which is sorted by source position.

        Example

        Code:

        fset := token.NewFileSet() // positions are relative to fset
        
        src := `package foo
        
        import (
            "fmt"
            "time"
        )
        
        func bar() {
            fmt.Println(time.Now())
        }`
        
        // Parse src but stop after processing the imports.
        f, err := parser.ParseFile(fset, "", src, parser.ImportsOnly)
        if err != nil {
            fmt.Println(err)
            return
        }
        
        // Print the imports from the file's AST.
        for _, s := range f.Imports {
            fmt.Println(s.Path.Value)
        }
        
        

        Output:

        "fmt"
        "time"
        

        type Mode

        A Mode value is a set of flags (or 0). They control the amount of source code parsed and other optional parser functionality.

        type Mode uint
        const (
            PackageClauseOnly    Mode             = 1 << iota // stop parsing after package clause
            ImportsOnly                                       // stop parsing after import declarations
            ParseComments                                     // parse comments and add them to AST
            Trace                                             // print a trace of parsed productions
            DeclarationErrors                                 // report declaration errors
            SpuriousErrors                                    // same as AllErrors, for backward-compatibility
            SkipObjectResolution                              // skip deprecated identifier resolution; see ParseFile
            AllErrors            = SpuriousErrors             // report all errors (not just the first 10 on different lines)
        )
        printer - Go Documentation Server
        ...

        Package printer

        import "go/printer"
        Overview
        Index
        Examples

        Overview ▾

        Package printer implements printing of AST nodes.

        func Fprint

        func Fprint(output io.Writer, fset *token.FileSet, node any) error

        Fprint "pretty-prints" an AST node to output. It calls Config.Fprint with default settings. Note that gofmt uses tabs for indentation but spaces for alignment; use format.Node (package go/format) for output that matches gofmt.

        Example

        Code:

        package printer_test
        
        import (
            "bytes"
            "fmt"
            "go/ast"
            "go/parser"
            "go/printer"
            "go/token"
            "strings"
        )
        
        func parseFunc(filename, functionname string) (fun *ast.FuncDecl, fset *token.FileSet) {
            fset = token.NewFileSet()
            if file, err := parser.ParseFile(fset, filename, nil, 0); err == nil {
                for _, d := range file.Decls {
                    if f, ok := d.(*ast.FuncDecl); ok && f.Name.Name == functionname {
                        fun = f
                        return
                    }
                }
            }
            panic("function not found")
        }
        
        func printSelf() {
            // Parse source file and extract the AST without comments for
            // this function, with position information referring to the
            // file set fset.
            funcAST, fset := parseFunc("example_test.go", "printSelf")
        
            // Print the function body into buffer buf.
            // The file set is provided to the printer so that it knows
            // about the original source formatting and can add additional
            // line breaks where they were present in the source.
            var buf bytes.Buffer
            printer.Fprint(&buf, fset, funcAST.Body)
        
            // Remove braces {} enclosing the function body, unindent,
            // and trim leading and trailing white space.
            s := buf.String()
            s = s[1 : len(s)-1]
            s = strings.TrimSpace(strings.ReplaceAll(s, "\n\t", "\n"))
        
            // Print the cleaned-up body text to stdout.
            fmt.Println(s)
        }
        
        func ExampleFprint() {
            printSelf()
        
            // Output:
            // funcAST, fset := parseFunc("example_test.go", "printSelf")
            //
            // var buf bytes.Buffer
            // printer.Fprint(&buf, fset, funcAST.Body)
            //
            // s := buf.String()
            // s = s[1 : len(s)-1]
            // s = strings.TrimSpace(strings.ReplaceAll(s, "\n\t", "\n"))
            //
            // fmt.Println(s)
        }
        

        type CommentedNode

        A CommentedNode bundles an AST node and corresponding comments. It may be provided as argument to any of the Fprint functions.

        type CommentedNode struct {
            Node     any // *ast.File, or ast.Expr, ast.Decl, ast.Spec, or ast.Stmt
            Comments []*ast.CommentGroup
        }
        

        type Config

        A Config node controls the output of Fprint.

        type Config struct {
            Mode     Mode // default: 0
            Tabwidth int  // default: 8
            Indent   int  // default: 0 (all code is indented at least by this much)
        }
        

        func (*Config) Fprint

        func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node any) error

        Fprint "pretty-prints" an AST node to output for a given configuration cfg. Position information is interpreted relative to the file set fset. The node type must be *ast.File, *CommentedNode, []ast.Decl, []ast.Stmt, or assignment-compatible to ast.Expr, ast.Decl, ast.Spec, or ast.Stmt.

        type Mode

        A Mode value is a set of flags (or 0). They control printing.

        type Mode uint
        const (
            RawFormat Mode = 1 << iota // do not use a tabwriter; if set, UseSpaces is ignored
            TabIndent                  // use tabs for indentation independent of UseSpaces
            UseSpaces                  // use spaces instead of tabs for alignment
            SourcePos                  // emit //line directives to preserve original source positions
        )
        scanner - Go Documentation Server
        ...

        Package scanner

        import "go/scanner"
        Overview
        Index
        Examples

        Overview ▾

        Package scanner implements a scanner for Go source text. It takes a []byte as source which can then be tokenized through repeated calls to the Scan method.

        func PrintError

        func PrintError(w io.Writer, err error)

        PrintError is a utility function that prints a list of errors to w, one error per line, if the err parameter is an ErrorList. Otherwise it prints the err string.

        type Error

        In an ErrorList, an error is represented by an *Error. The position Pos, if valid, points to the beginning of the offending token, and the error condition is described by Msg.

        type Error struct {
            Pos token.Position
            Msg string
        }
        

        func (Error) Error

        func (e Error) Error() string

        Error implements the error interface.

        type ErrorHandler

        An ErrorHandler may be provided to Scanner.Init. If a syntax error is encountered and a handler was installed, the handler is called with a position and an error message. The position points to the beginning of the offending token.

        type ErrorHandler func(pos token.Position, msg string)

        type ErrorList

        ErrorList is a list of *Errors. The zero value for an ErrorList is an empty ErrorList ready to use.

        type ErrorList []*Error

        func (*ErrorList) Add

        func (p *ErrorList) Add(pos token.Position, msg string)

        Add adds an Error with given position and error message to an ErrorList.

        func (ErrorList) Err

        func (p ErrorList) Err() error

        Err returns an error equivalent to this error list. If the list is empty, Err returns nil.

        func (ErrorList) Error

        func (p ErrorList) Error() string

        An ErrorList implements the error interface.

        func (ErrorList) Len

        func (p ErrorList) Len() int

        ErrorList implements the sort Interface.

        func (ErrorList) Less

        func (p ErrorList) Less(i, j int) bool

        func (*ErrorList) RemoveMultiples

        func (p *ErrorList) RemoveMultiples()

        RemoveMultiples sorts an ErrorList and removes all but the first error per line.

        func (*ErrorList) Reset

        func (p *ErrorList) Reset()

        Reset resets an ErrorList to no errors.

        func (ErrorList) Sort

        func (p ErrorList) Sort()

        Sort sorts an ErrorList. *Error entries are sorted by position, other errors are sorted by error message, and before any *Error entry.

        func (ErrorList) Swap

        func (p ErrorList) Swap(i, j int)

        type Mode

        A mode value is a set of flags (or 0). They control scanner behavior.

        type Mode uint
        const (
            ScanComments Mode = 1 << iota // return comments as COMMENT tokens
        
        )

        type Scanner

        A Scanner holds the scanner's internal state while processing a given text. It can be allocated as part of another data structure but must be initialized via Scanner.Init before use.

        type Scanner struct {
        
            // public state - ok to modify
            ErrorCount int // number of errors encountered
            // contains filtered or unexported fields
        }
        

        func (*Scanner) Init

        func (s *Scanner) Init(file *token.File, src []byte, err ErrorHandler, mode Mode)

        Init prepares the scanner s to tokenize the text src by setting the scanner at the beginning of src. The scanner uses the file set file for position information and it adds line information for each line. It is ok to re-use the same file when re-scanning the same file as line information which is already present is ignored. Init causes a panic if the file size does not match the src size.

        Calls to Scanner.Scan will invoke the error handler err if they encounter a syntax error and err is not nil. Also, for each error encountered, the Scanner field ErrorCount is incremented by one. The mode parameter determines how comments are handled.

        Note that Init may call err if there is an error in the first character of the file.

        func (*Scanner) Scan

        func (s *Scanner) Scan() (pos token.Pos, tok token.Token, lit string)

        Scan scans the next token and returns the token position, the token, and its literal string if applicable. The source end is indicated by token.EOF.

        If the returned token is a literal (token.IDENT, token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING) or token.COMMENT, the literal string has the corresponding value.

        If the returned token is a keyword, the literal string is the keyword.

        If the returned token is token.SEMICOLON, the corresponding literal string is ";" if the semicolon was present in the source, and "\n" if the semicolon was inserted because of a newline or at EOF.

        If the returned token is token.ILLEGAL, the literal string is the offending character.

        In all other cases, Scan returns an empty literal string.

        For more tolerant parsing, Scan will return a valid token if possible even if a syntax error was encountered. Thus, even if the resulting token sequence contains no illegal tokens, a client may not assume that no error occurred. Instead it must check the scanner's ErrorCount or the number of calls of the error handler, if there was one installed.

        Scan adds line information to the file added to the file set with Init. Token positions are relative to that file and thus relative to the file set.

        Example

        Code:

        // src is the input that we want to tokenize.
        src := []byte("cos(x) + 1i*sin(x) // Euler")
        
        // Initialize the scanner.
        var s scanner.Scanner
        fset := token.NewFileSet()                      // positions are relative to fset
        file := fset.AddFile("", fset.Base(), len(src)) // register input "file"
        s.Init(file, src, nil /* no error handler */, scanner.ScanComments)
        
        // Repeated calls to Scan yield the token sequence found in the input.
        for {
            pos, tok, lit := s.Scan()
            if tok == token.EOF {
                break
            }
            fmt.Printf("%s\t%s\t%q\n", fset.Position(pos), tok, lit)
        }
        
        

        Output:

        1:1	IDENT	"cos"
        1:4	(	""
        1:5	IDENT	"x"
        1:6	)	""
        1:8	+	""
        1:10	IMAG	"1i"
        1:12	*	""
        1:13	IDENT	"sin"
        1:16	(	""
        1:17	IDENT	"x"
        1:18	)	""
        1:20	COMMENT	"// Euler"
        1:28	;	"\n"
        
        token - Go Documentation Server
        ...

        Package token

        import "go/token"
        Overview
        Index
        Examples

        Overview ▾

        Package token defines constants representing the lexical tokens of the Go programming language and basic operations on tokens (printing, predicates).

        Example (RetrievePositionInfo)

        Code:

        fset := token.NewFileSet()
        
        const src = `package main
        
        import "fmt"
        
        import "go/token"
        
        
        type p = token.Pos
        
        const bad = token.NoPos
        
        
        func ok(pos p) bool {
            return pos != bad
        }
        
        /*line :7:9*/func main() {
            fmt.Println(ok(bad) == bad.IsValid())
        }
        `
        
        f, err := parser.ParseFile(fset, "main.go", src, 0)
        if err != nil {
            fmt.Println(err)
            return
        }
        
        // Print the location and kind of each declaration in f.
        for _, decl := range f.Decls {
            // Get the filename, line, and column back via the file set.
            // We get both the relative and absolute position.
            // The relative position is relative to the last line directive.
            // The absolute position is the exact position in the source.
            pos := decl.Pos()
            relPosition := fset.Position(pos)
            absPosition := fset.PositionFor(pos, false)
        
            // Either a FuncDecl or GenDecl, since we exit on error.
            kind := "func"
            if gen, ok := decl.(*ast.GenDecl); ok {
                kind = gen.Tok.String()
            }
        
            // If the relative and absolute positions differ, show both.
            fmtPosition := relPosition.String()
            if relPosition != absPosition {
                fmtPosition += "[" + absPosition.String() + "]"
            }
        
            fmt.Printf("%s: %s\n", fmtPosition, kind)
        }
        
        

        Output:

        main.go:3:1: import
        main.go:5:1: import
        main.go:1:5[main.go:8:1]: type
        main.go:3:1[main.go:10:1]: const
        fake.go:42:11[main.go:13:1]: func
        fake.go:7:9[main.go:17:14]: func
        

        Index ▾

        Constants
        func IsExported(name string) bool
        func IsIdentifier(name string) bool
        func IsKeyword(name string) bool
        type File
            func (f *File) AddLine(offset int)
            func (f *File) AddLineColumnInfo(offset int, filename string, line, column int)
            func (f *File) AddLineInfo(offset int, filename string, line int)
            func (f *File) Base() int
            func (f *File) Line(p Pos) int
            func (f *File) LineCount() int
            func (f *File) LineStart(line int) Pos
            func (f *File) Lines() []int
            func (f *File) MergeLine(line int)
            func (f *File) Name() string
            func (f *File) Offset(p Pos) int
            func (f *File) Pos(offset int) Pos
            func (f *File) Position(p Pos) (pos Position)
            func (f *File) PositionFor(p Pos, adjusted bool) (pos Position)
            func (f *File) SetLines(lines []int) bool
            func (f *File) SetLinesForContent(content []byte)
            func (f *File) Size() int
        type FileSet
            func NewFileSet() *FileSet
            func (s *FileSet) AddFile(filename string, base, size int) *File
            func (s *FileSet) Base() int
            func (s *FileSet) File(p Pos) (f *File)
            func (s *FileSet) Iterate(f func(*File) bool)
            func (s *FileSet) Position(p Pos) (pos Position)
            func (s *FileSet) PositionFor(p Pos, adjusted bool) (pos Position)
            func (s *FileSet) Read(decode func(any) error) error
            func (s *FileSet) RemoveFile(file *File)
            func (s *FileSet) Write(encode func(any) error) error
        type Pos
            func (p Pos) IsValid() bool
        type Position
            func (pos *Position) IsValid() bool
            func (pos Position) String() string
        type Token
            func Lookup(ident string) Token
            func (tok Token) IsKeyword() bool
            func (tok Token) IsLiteral() bool
            func (tok Token) IsOperator() bool
            func (op Token) Precedence() int
            func (tok Token) String() string

        Examples

        Package (RetrievePositionInfo)

        Package files

        position.go serialize.go token.go

        Constants

        A set of constants for precedence-based expression parsing. Non-operators have lowest precedence, followed by operators starting with precedence 1 up to unary operators. The highest precedence serves as "catch-all" precedence for selector, indexing, and other operator and delimiter tokens.

        const (
            LowestPrec  = 0 // non-operators
            UnaryPrec   = 6
            HighestPrec = 7
        )

        func IsExported

        func IsExported(name string) bool

        IsExported reports whether name starts with an upper-case letter.

        func IsIdentifier

        func IsIdentifier(name string) bool

        IsIdentifier reports whether name is a Go identifier, that is, a non-empty string made up of letters, digits, and underscores, where the first character is not a digit. Keywords are not identifiers.

        func IsKeyword

        func IsKeyword(name string) bool

        IsKeyword reports whether name is a Go keyword, such as "func" or "return".

        type File

        A File is a handle for a file belonging to a FileSet. A File has a name, size, and line offset table.

        type File struct {
            // contains filtered or unexported fields
        }
        

        func (*File) AddLine

        func (f *File) AddLine(offset int)

        AddLine adds the line offset for a new line. The line offset must be larger than the offset for the previous line and smaller than the file size; otherwise the line offset is ignored.

        func (*File) AddLineColumnInfo

        func (f *File) AddLineColumnInfo(offset int, filename string, line, column int)

        AddLineColumnInfo adds alternative file, line, and column number information for a given file offset. The offset must be larger than the offset for the previously added alternative line info and smaller than the file size; otherwise the information is ignored.

        AddLineColumnInfo is typically used to register alternative position information for line directives such as //line filename:line:column.

        func (*File) AddLineInfo

        func (f *File) AddLineInfo(offset int, filename string, line int)

        AddLineInfo is like File.AddLineColumnInfo with a column = 1 argument. It is here for backward-compatibility for code prior to Go 1.11.

        func (*File) Base

        func (f *File) Base() int

        Base returns the base offset of file f as registered with AddFile.

        func (*File) Line

        func (f *File) Line(p Pos) int

        Line returns the line number for the given file position p; p must be a Pos value in that file or NoPos.

        func (*File) LineCount

        func (f *File) LineCount() int

        LineCount returns the number of lines in file f.

        func (*File) LineStart

        func (f *File) LineStart(line int) Pos

        LineStart returns the Pos value of the start of the specified line. It ignores any alternative positions set using File.AddLineColumnInfo. LineStart panics if the 1-based line number is invalid.

        func (*File) Lines

        func (f *File) Lines() []int

        Lines returns the effective line offset table of the form described by File.SetLines. Callers must not mutate the result.

        func (*File) MergeLine

        func (f *File) MergeLine(line int)

        MergeLine merges a line with the following line. It is akin to replacing the newline character at the end of the line with a space (to not change the remaining offsets). To obtain the line number, consult e.g. [Position.Line]. MergeLine will panic if given an invalid line number.

        func (*File) Name

        func (f *File) Name() string

        Name returns the file name of file f as registered with AddFile.

        func (*File) Offset

        func (f *File) Offset(p Pos) int

        Offset returns the offset for the given file position p; p must be a valid Pos value in that file. f.Offset(f.Pos(offset)) == offset.

        func (*File) Pos

        func (f *File) Pos(offset int) Pos

        Pos returns the Pos value for the given file offset; the offset must be <= f.Size(). f.Pos(f.Offset(p)) == p.

        func (*File) Position

        func (f *File) Position(p Pos) (pos Position)

        Position returns the Position value for the given file position p. Calling f.Position(p) is equivalent to calling f.PositionFor(p, true).

        func (*File) PositionFor

        func (f *File) PositionFor(p Pos, adjusted bool) (pos Position)

        PositionFor returns the Position value for the given file position p. If adjusted is set, the position may be adjusted by position-altering //line comments; otherwise those comments are ignored. p must be a Pos value in f or NoPos.

        func (*File) SetLines

        func (f *File) SetLines(lines []int) bool

        SetLines sets the line offsets for a file and reports whether it succeeded. The line offsets are the offsets of the first character of each line; for instance for the content "ab\nc\n" the line offsets are {0, 3}. An empty file has an empty line offset table. Each line offset must be larger than the offset for the previous line and smaller than the file size; otherwise SetLines fails and returns false. Callers must not mutate the provided slice after SetLines returns.

        func (*File) SetLinesForContent

        func (f *File) SetLinesForContent(content []byte)

        SetLinesForContent sets the line offsets for the given file content. It ignores position-altering //line comments.

        func (*File) Size

        func (f *File) Size() int

        Size returns the size of file f as registered with AddFile.

        type FileSet

        A FileSet represents a set of source files. Methods of file sets are synchronized; multiple goroutines may invoke them concurrently.

        The byte offsets for each file in a file set are mapped into distinct (integer) intervals, one interval [base, base+size] per file. FileSet.Base represents the first byte in the file, and size is the corresponding file size. A Pos value is a value in such an interval. By determining the interval a Pos value belongs to, the file, its file base, and thus the byte offset (position) the Pos value is representing can be computed.

        When adding a new file, a file base must be provided. That can be any integer value that is past the end of any interval of any file already in the file set. For convenience, FileSet.Base provides such a value, which is simply the end of the Pos interval of the most recently added file, plus one. Unless there is a need to extend an interval later, using the FileSet.Base should be used as argument for FileSet.AddFile.

        A File may be removed from a FileSet when it is no longer needed. This may reduce memory usage in a long-running application.

        type FileSet struct {
            // contains filtered or unexported fields
        }
        

        func NewFileSet

        func NewFileSet() *FileSet

        NewFileSet creates a new file set.

        func (*FileSet) AddFile

        func (s *FileSet) AddFile(filename string, base, size int) *File

        AddFile adds a new file with a given filename, base offset, and file size to the file set s and returns the file. Multiple files may have the same name. The base offset must not be smaller than the FileSet.Base, and size must not be negative. As a special case, if a negative base is provided, the current value of the FileSet.Base is used instead.

        Adding the file will set the file set's FileSet.Base value to base + size + 1 as the minimum base value for the next file. The following relationship exists between a Pos value p for a given file offset offs:

        int(p) = base + offs
        

        with offs in the range [0, size] and thus p in the range [base, base+size]. For convenience, File.Pos may be used to create file-specific position values from a file offset.

        func (*FileSet) Base

        func (s *FileSet) Base() int

        Base returns the minimum base offset that must be provided to FileSet.AddFile when adding the next file.

        func (*FileSet) File

        func (s *FileSet) File(p Pos) (f *File)

        File returns the file that contains the position p. If no such file is found (for instance for p == NoPos), the result is nil.

        func (*FileSet) Iterate

        func (s *FileSet) Iterate(f func(*File) bool)

        Iterate calls f for the files in the file set in the order they were added until f returns false.

        func (*FileSet) Position

        func (s *FileSet) Position(p Pos) (pos Position)

        Position converts a Pos p in the fileset into a Position value. Calling s.Position(p) is equivalent to calling s.PositionFor(p, true).

        func (*FileSet) PositionFor

        func (s *FileSet) PositionFor(p Pos, adjusted bool) (pos Position)

        PositionFor converts a Pos p in the fileset into a Position value. If adjusted is set, the position may be adjusted by position-altering //line comments; otherwise those comments are ignored. p must be a Pos value in s or NoPos.

        func (*FileSet) Read

        func (s *FileSet) Read(decode func(any) error) error

        Read calls decode to deserialize a file set into s; s must not be nil.

        func (*FileSet) RemoveFile

        func (s *FileSet) RemoveFile(file *File)

        RemoveFile removes a file from the FileSet so that subsequent queries for its Pos interval yield a negative result. This reduces the memory usage of a long-lived FileSet that encounters an unbounded stream of files.

        Removing a file that does not belong to the set has no effect.

        func (*FileSet) Write

        func (s *FileSet) Write(encode func(any) error) error

        Write calls encode to serialize the file set s.

        type Pos

        Pos is a compact encoding of a source position within a file set. It can be converted into a Position for a more convenient, but much larger, representation.

        The Pos value for a given file is a number in the range [base, base+size], where base and size are specified when a file is added to the file set. The difference between a Pos value and the corresponding file base corresponds to the byte offset of that position (represented by the Pos value) from the beginning of the file. Thus, the file base offset is the Pos value representing the first byte in the file.

        To create the Pos value for a specific source offset (measured in bytes), first add the respective file to the current file set using FileSet.AddFile and then call File.Pos(offset) for that file. Given a Pos value p for a specific file set fset, the corresponding Position value is obtained by calling fset.Position(p).

        Pos values can be compared directly with the usual comparison operators: If two Pos values p and q are in the same file, comparing p and q is equivalent to comparing the respective source file offsets. If p and q are in different files, p < q is true if the file implied by p was added to the respective file set before the file implied by q.

        type Pos int

        The zero value for Pos is NoPos; there is no file and line information associated with it, and NoPos.IsValid() is false. NoPos is always smaller than any other Pos value. The corresponding Position value for NoPos is the zero value for Position.

        const NoPos Pos = 0

        func (Pos) IsValid

        func (p Pos) IsValid() bool

        IsValid reports whether the position is valid.

        type Position

        Position describes an arbitrary source position including the file, line, and column location. A Position is valid if the line number is > 0.

        type Position struct {
            Filename string // filename, if any
            Offset   int    // offset, starting at 0
            Line     int    // line number, starting at 1
            Column   int    // column number, starting at 1 (byte count)
        }
        

        func (*Position) IsValid

        func (pos *Position) IsValid() bool

        IsValid reports whether the position is valid.

        func (Position) String

        func (pos Position) String() string

        String returns a string in one of several forms:

        file:line:column    valid position with file name
        file:line           valid position with file name but no column (column == 0)
        line:column         valid position without file name
        line                valid position without file name and no column (column == 0)
        file                invalid position with file name
        -                   invalid position without file name
        

        type Token

        Token is the set of lexical tokens of the Go programming language.

        type Token int

        The list of tokens.

        const (
            // Special tokens
            ILLEGAL Token = iota
            EOF
            COMMENT
        
            // Identifiers and basic type literals
            // (these tokens stand for classes of literals)
            IDENT  // main
            INT    // 12345
            FLOAT  // 123.45
            IMAG   // 123.45i
            CHAR   // 'a'
            STRING // "abc"
        
            // Operators and delimiters
            ADD // +
            SUB // -
            MUL // *
            QUO // /
            REM // %
        
            AND     // &
            OR      // |
            XOR     // ^
            SHL     // <<
            SHR     // >>
            AND_NOT // &^
        
            ADD_ASSIGN // +=
            SUB_ASSIGN // -=
            MUL_ASSIGN // *=
            QUO_ASSIGN // /=
            REM_ASSIGN // %=
        
            AND_ASSIGN     // &=
            OR_ASSIGN      // |=
            XOR_ASSIGN     // ^=
            SHL_ASSIGN     // <<=
            SHR_ASSIGN     // >>=
            AND_NOT_ASSIGN // &^=
        
            LAND  // &&
            LOR   // ||
            ARROW // <-
            INC   // ++
            DEC   // --
        
            EQL    // ==
            LSS    // <
            GTR    // >
            ASSIGN // =
            NOT    // !
        
            NEQ      // !=
            LEQ      // <=
            GEQ      // >=
            DEFINE   // :=
            ELLIPSIS // ...
        
            LPAREN // (
            LBRACK // [
            LBRACE // {
            COMMA  // ,
            PERIOD // .
        
            RPAREN    // )
            RBRACK    // ]
            RBRACE    // }
            SEMICOLON // ;
            COLON     // :
        
            // Keywords
            BREAK
            CASE
            CHAN
            CONST
            CONTINUE
        
            DEFAULT
            DEFER
            ELSE
            FALLTHROUGH
            FOR
        
            FUNC
            GO
            GOTO
            IF
            IMPORT
        
            INTERFACE
            MAP
            PACKAGE
            RANGE
            RETURN
        
            SELECT
            STRUCT
            SWITCH
            TYPE
            VAR
        
            // additional tokens, handled in an ad-hoc manner
            TILDE
        )

        func Lookup

        func Lookup(ident string) Token

        Lookup maps an identifier to its keyword token or IDENT (if not a keyword).

        func (Token) IsKeyword

        func (tok Token) IsKeyword() bool

        IsKeyword returns true for tokens corresponding to keywords; it returns false otherwise.

        func (Token) IsLiteral

        func (tok Token) IsLiteral() bool

        IsLiteral returns true for tokens corresponding to identifiers and basic type literals; it returns false otherwise.

        func (Token) IsOperator

        func (tok Token) IsOperator() bool

        IsOperator returns true for tokens corresponding to operators and delimiters; it returns false otherwise.

        func (Token) Precedence

        func (op Token) Precedence() int

        Precedence returns the operator precedence of the binary operator op. If op is not a binary operator, the result is LowestPrecedence.

        func (Token) String

        func (tok Token) String() string

        String returns the string corresponding to the token tok. For operators, delimiters, and keywords the string is the actual token character sequence (e.g., for the token ADD, the string is "+"). For all other tokens the string corresponds to the token constant name (e.g. for the token IDENT, the string is "IDENT").

        types - Go Documentation Server
        ...

        Package types

        import "go/types"
        Overview
        Index
        Examples

        Overview ▾

        Package types declares the data types and implements the algorithms for type-checking of Go packages. Use Config.Check to invoke the type checker for a package. Alternatively, create a new type checker with NewChecker and invoke it incrementally by calling Checker.Files.

        Type-checking consists of several interdependent phases:

        Name resolution maps each identifier (ast.Ident) in the program to the language object (Object) it denotes. Use Info.{Defs,Uses,Implicits} for the results of name resolution.

        Constant folding computes the exact constant value (constant.Value) for every expression (ast.Expr) that is a compile-time constant. Use Info.Types[expr].Value for the results of constant folding.

        Type inference computes the type (Type) of every expression (ast.Expr) and checks for compliance with the language specification. Use [Info.Types][expr].Type for the results of type inference.

        For a tutorial, see https://golang.org/s/types-tutorial.

        Index ▾

        Variables
        func AssertableTo(V *Interface, T Type) bool
        func AssignableTo(V, T Type) bool
        func CheckExpr(fset *token.FileSet, pkg *Package, pos token.Pos, expr ast.Expr, info *Info) (err error)
        func Comparable(T Type) bool
        func ConvertibleTo(V, T Type) bool
        func DefPredeclaredTestFuncs()
        func ExprString(x ast.Expr) string
        func Id(pkg *Package, name string) string
        func Identical(x, y Type) bool
        func IdenticalIgnoreTags(x, y Type) bool
        func Implements(V Type, T *Interface) bool
        func IsInterface(t Type) bool
        func ObjectString(obj Object, qf Qualifier) string
        func Satisfies(V Type, T *Interface) bool
        func SelectionString(s *Selection, qf Qualifier) string
        func TypeString(typ Type, qf Qualifier) string
        func WriteExpr(buf *bytes.Buffer, x ast.Expr)
        func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier)
        func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier)
        type Alias
            func NewAlias(obj *TypeName, rhs Type) *Alias
            func (a *Alias) Obj() *TypeName
            func (a *Alias) String() string
            func (a *Alias) Underlying() Type
        type ArgumentError
            func (e *ArgumentError) Error() string
            func (e *ArgumentError) Unwrap() error
        type Array
            func NewArray(elem Type, len int64) *Array
            func (a *Array) Elem() Type
            func (a *Array) Len() int64
            func (a *Array) String() string
            func (a *Array) Underlying() Type
        type Basic
            func (b *Basic) Info() BasicInfo
            func (b *Basic) Kind() BasicKind
            func (b *Basic) Name() string
            func (b *Basic) String() string
            func (b *Basic) Underlying() Type
        type BasicInfo
        type BasicKind
        type Builtin
            func (obj *Builtin) Exported() bool
            func (obj *Builtin) Id() string
            func (obj *Builtin) Name() string
            func (obj *Builtin) Parent() *Scope
            func (obj *Builtin) Pkg() *Package
            func (obj *Builtin) Pos() token.Pos
            func (obj *Builtin) String() string
            func (obj *Builtin) Type() Type
        type Chan
            func NewChan(dir ChanDir, elem Type) *Chan
            func (c *Chan) Dir() ChanDir
            func (c *Chan) Elem() Type
            func (c *Chan) String() string
            func (c *Chan) Underlying() Type
        type ChanDir
        type Checker
            func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker
            func (check *Checker) Files(files []*ast.File) error
        type Config
            func (conf *Config) Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error)
        type Const
            func NewConst(pos token.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const
            func (obj *Const) Exported() bool
            func (obj *Const) Id() string
            func (obj *Const) Name() string
            func (obj *Const) Parent() *Scope
            func (obj *Const) Pkg() *Package
            func (obj *Const) Pos() token.Pos
            func (obj *Const) String() string
            func (obj *Const) Type() Type
            func (obj *Const) Val() constant.Value
        type Context
            func NewContext() *Context
        type Error
            func (err Error) Error() string
        type Func
            func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)
            func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func
            func (obj *Func) Exported() bool
            func (obj *Func) FullName() string
            func (obj *Func) Id() string
            func (obj *Func) Name() string
            func (obj *Func) Origin() *Func
            func (obj *Func) Parent() *Scope
            func (obj *Func) Pkg() *Package
            func (obj *Func) Pos() token.Pos
            func (obj *Func) Scope() *Scope
            func (obj *Func) String() string
            func (obj *Func) Type() Type
        type ImportMode
        type Importer
        type ImporterFrom
        type Info
            func (info *Info) ObjectOf(id *ast.Ident) Object
            func (info *Info) PkgNameOf(imp *ast.ImportSpec) *PkgName
            func (info *Info) TypeOf(e ast.Expr) Type
        type Initializer
            func (init *Initializer) String() string
        type Instance
        type Interface
            func NewInterface(methods []*Func, embeddeds []*Named) *Interface
            func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface
            func (t *Interface) Complete() *Interface
            func (t *Interface) Embedded(i int) *Named
            func (t *Interface) EmbeddedType(i int) Type
            func (t *Interface) Empty() bool
            func (t *Interface) ExplicitMethod(i int) *Func
            func (t *Interface) IsComparable() bool
            func (t *Interface) IsImplicit() bool
            func (t *Interface) IsMethodSet() bool
            func (t *Interface) MarkImplicit()
            func (t *Interface) Method(i int) *Func
            func (t *Interface) NumEmbeddeds() int
            func (t *Interface) NumExplicitMethods() int
            func (t *Interface) NumMethods() int
            func (t *Interface) String() string
            func (t *Interface) Underlying() Type
        type Label
            func NewLabel(pos token.Pos, pkg *Package, name string) *Label
            func (obj *Label) Exported() bool
            func (obj *Label) Id() string
            func (obj *Label) Name() string
            func (obj *Label) Parent() *Scope
            func (obj *Label) Pkg() *Package
            func (obj *Label) Pos() token.Pos
            func (obj *Label) String() string
            func (obj *Label) Type() Type
        type Map
            func NewMap(key, elem Type) *Map
            func (m *Map) Elem() Type
            func (m *Map) Key() Type
            func (t *Map) String() string
            func (t *Map) Underlying() Type
        type MethodSet
            func NewMethodSet(T Type) *MethodSet
            func (s *MethodSet) At(i int) *Selection
            func (s *MethodSet) Len() int
            func (s *MethodSet) Lookup(pkg *Package, name string) *Selection
            func (s *MethodSet) String() string
        type Named
            func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named
            func (t *Named) AddMethod(m *Func)
            func (t *Named) Method(i int) *Func
            func (t *Named) NumMethods() int
            func (t *Named) Obj() *TypeName
            func (t *Named) Origin() *Named
            func (t *Named) SetTypeParams(tparams []*TypeParam)
            func (t *Named) SetUnderlying(underlying Type)
            func (t *Named) String() string
            func (t *Named) TypeArgs() *TypeList
            func (t *Named) TypeParams() *TypeParamList
            func (t *Named) Underlying() Type
        type Nil
            func (obj *Nil) Exported() bool
            func (obj *Nil) Id() string
            func (obj *Nil) Name() string
            func (obj *Nil) Parent() *Scope
            func (obj *Nil) Pkg() *Package
            func (obj *Nil) Pos() token.Pos
            func (obj *Nil) String() string
            func (obj *Nil) Type() Type
        type Object
            func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool)
        type Package
            func NewPackage(path, name string) *Package
            func (pkg *Package) Complete() bool
            func (pkg *Package) GoVersion() string
            func (pkg *Package) Imports() []*Package
            func (pkg *Package) MarkComplete()
            func (pkg *Package) Name() string
            func (pkg *Package) Path() string
            func (pkg *Package) Scope() *Scope
            func (pkg *Package) SetImports(list []*Package)
            func (pkg *Package) SetName(name string)
            func (pkg *Package) String() string
        type PkgName
            func NewPkgName(pos token.Pos, pkg *Package, name string, imported *Package) *PkgName
            func (obj *PkgName) Exported() bool
            func (obj *PkgName) Id() string
            func (obj *PkgName) Imported() *Package
            func (obj *PkgName) Name() string
            func (obj *PkgName) Parent() *Scope
            func (obj *PkgName) Pkg() *Package
            func (obj *PkgName) Pos() token.Pos
            func (obj *PkgName) String() string
            func (obj *PkgName) Type() Type
        type Pointer
            func NewPointer(elem Type) *Pointer
            func (p *Pointer) Elem() Type
            func (p *Pointer) String() string
            func (p *Pointer) Underlying() Type
        type Qualifier
            func RelativeTo(pkg *Package) Qualifier
        type Scope
            func NewScope(parent *Scope, pos, end token.Pos, comment string) *Scope
            func (s *Scope) Child(i int) *Scope
            func (s *Scope) Contains(pos token.Pos) bool
            func (s *Scope) End() token.Pos
            func (s *Scope) Innermost(pos token.Pos) *Scope
            func (s *Scope) Insert(obj Object) Object
            func (s *Scope) Len() int
            func (s *Scope) Lookup(name string) Object
            func (s *Scope) LookupParent(name string, pos token.Pos) (*Scope, Object)
            func (s *Scope) Names() []string
            func (s *Scope) NumChildren() int
            func (s *Scope) Parent() *Scope
            func (s *Scope) Pos() token.Pos
            func (s *Scope) String() string
            func (s *Scope) WriteTo(w io.Writer, n int, recurse bool)
        type Selection
            func (s *Selection) Index() []int
            func (s *Selection) Indirect() bool
            func (s *Selection) Kind() SelectionKind
            func (s *Selection) Obj() Object
            func (s *Selection) Recv() Type
            func (s *Selection) String() string
            func (s *Selection) Type() Type
        type SelectionKind
        type Signature
            func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature
            func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature
            func (s *Signature) Params() *Tuple
            func (s *Signature) Recv() *Var
            func (s *Signature) RecvTypeParams() *TypeParamList
            func (s *Signature) Results() *Tuple
            func (t *Signature) String() string
            func (s *Signature) TypeParams() *TypeParamList
            func (t *Signature) Underlying() Type
            func (s *Signature) Variadic() bool
        type Sizes
            func SizesFor(compiler, arch string) Sizes
        type Slice
            func NewSlice(elem Type) *Slice
            func (s *Slice) Elem() Type
            func (s *Slice) String() string
            func (s *Slice) Underlying() Type
        type StdSizes
            func (s *StdSizes) Alignof(T Type) (result int64)
            func (s *StdSizes) Offsetsof(fields []*Var) []int64
            func (s *StdSizes) Sizeof(T Type) int64
        type Struct
            func NewStruct(fields []*Var, tags []string) *Struct
            func (s *Struct) Field(i int) *Var
            func (s *Struct) NumFields() int
            func (t *Struct) String() string
            func (s *Struct) Tag(i int) string
            func (t *Struct) Underlying() Type
        type Term
            func NewTerm(tilde bool, typ Type) *Term
            func (t *Term) String() string
            func (t *Term) Tilde() bool
            func (t *Term) Type() Type
        type Tuple
            func NewTuple(x ...*Var) *Tuple
            func (t *Tuple) At(i int) *Var
            func (t *Tuple) Len() int
            func (t *Tuple) String() string
            func (t *Tuple) Underlying() Type
        type Type
            func Default(t Type) Type
            func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error)
            func Unalias(t Type) Type
        type TypeAndValue
            func Eval(fset *token.FileSet, pkg *Package, pos token.Pos, expr string) (_ TypeAndValue, err error)
            func (tv TypeAndValue) Addressable() bool
            func (tv TypeAndValue) Assignable() bool
            func (tv TypeAndValue) HasOk() bool
            func (tv TypeAndValue) IsBuiltin() bool
            func (tv TypeAndValue) IsNil() bool
            func (tv TypeAndValue) IsType() bool
            func (tv TypeAndValue) IsValue() bool
            func (tv TypeAndValue) IsVoid() bool
        type TypeList
            func (l *TypeList) At(i int) Type
            func (l *TypeList) Len() int
        type TypeName
            func NewTypeName(pos token.Pos, pkg *Package, name string, typ Type) *TypeName
            func (obj *TypeName) Exported() bool
            func (obj *TypeName) Id() string
            func (obj *TypeName) IsAlias() bool
            func (obj *TypeName) Name() string
            func (obj *TypeName) Parent() *Scope
            func (obj *TypeName) Pkg() *Package
            func (obj *TypeName) Pos() token.Pos
            func (obj *TypeName) String() string
            func (obj *TypeName) Type() Type
        type TypeParam
            func NewTypeParam(obj *TypeName, constraint Type) *TypeParam
            func (t *TypeParam) Constraint() Type
            func (t *TypeParam) Index() int
            func (t *TypeParam) Obj() *TypeName
            func (t *TypeParam) SetConstraint(bound Type)
            func (t *TypeParam) String() string
            func (t *TypeParam) Underlying() Type
        type TypeParamList
            func (l *TypeParamList) At(i int) *TypeParam
            func (l *TypeParamList) Len() int
        type Union
            func NewUnion(terms []*Term) *Union
            func (u *Union) Len() int
            func (u *Union) String() string
            func (u *Union) Term(i int) *Term
            func (u *Union) Underlying() Type
        type Var
            func NewField(pos token.Pos, pkg *Package, name string, typ Type, embedded bool) *Var
            func NewParam(pos token.Pos, pkg *Package, name string, typ Type) *Var
            func NewVar(pos token.Pos, pkg *Package, name string, typ Type) *Var
            func (obj *Var) Anonymous() bool
            func (obj *Var) Embedded() bool
            func (obj *Var) Exported() bool
            func (obj *Var) Id() string
            func (obj *Var) IsField() bool
            func (obj *Var) Name() string
            func (obj *Var) Origin() *Var
            func (obj *Var) Parent() *Scope
            func (obj *Var) Pkg() *Package
            func (obj *Var) Pos() token.Pos
            func (obj *Var) String() string
            func (obj *Var) Type() Type

        Examples

        Info
        MethodSet
        Scope

        Package files

        alias.go api.go api_predicates.go array.go assignments.go basic.go builtins.go call.go chan.go check.go const.go context.go conversions.go decl.go errors.go eval.go expr.go exprstring.go gccgosizes.go gcsizes.go generate.go index.go infer.go initorder.go instantiate.go interface.go labels.go lookup.go map.go methodset.go mono.go named.go object.go objset.go operand.go package.go pointer.go predicates.go resolver.go return.go scope.go selection.go signature.go sizes.go slice.go stmt.go struct.go subst.go termlist.go tuple.go type.go typelists.go typeparam.go typeset.go typestring.go typeterm.go typexpr.go under.go unify.go union.go universe.go util.go validtype.go version.go

        Variables

        Typ contains the predeclared *Basic types indexed by their corresponding BasicKind.

        The *Basic type for Typ[Byte] will have the name "uint8". Use Universe.Lookup("byte").Type() to obtain the specific alias basic type named "byte" (and analogous for "rune").

        var Typ = []*Basic{
            Invalid: {Invalid, 0, "invalid type"},
        
            Bool:          {Bool, IsBoolean, "bool"},
            Int:           {Int, IsInteger, "int"},
            Int8:          {Int8, IsInteger, "int8"},
            Int16:         {Int16, IsInteger, "int16"},
            Int32:         {Int32, IsInteger, "int32"},
            Int64:         {Int64, IsInteger, "int64"},
            Uint:          {Uint, IsInteger | IsUnsigned, "uint"},
            Uint8:         {Uint8, IsInteger | IsUnsigned, "uint8"},
            Uint16:        {Uint16, IsInteger | IsUnsigned, "uint16"},
            Uint32:        {Uint32, IsInteger | IsUnsigned, "uint32"},
            Uint64:        {Uint64, IsInteger | IsUnsigned, "uint64"},
            Uintptr:       {Uintptr, IsInteger | IsUnsigned, "uintptr"},
            Float32:       {Float32, IsFloat, "float32"},
            Float64:       {Float64, IsFloat, "float64"},
            Complex64:     {Complex64, IsComplex, "complex64"},
            Complex128:    {Complex128, IsComplex, "complex128"},
            String:        {String, IsString, "string"},
            UnsafePointer: {UnsafePointer, 0, "Pointer"},
        
            UntypedBool:    {UntypedBool, IsBoolean | IsUntyped, "untyped bool"},
            UntypedInt:     {UntypedInt, IsInteger | IsUntyped, "untyped int"},
            UntypedRune:    {UntypedRune, IsInteger | IsUntyped, "untyped rune"},
            UntypedFloat:   {UntypedFloat, IsFloat | IsUntyped, "untyped float"},
            UntypedComplex: {UntypedComplex, IsComplex | IsUntyped, "untyped complex"},
            UntypedString:  {UntypedString, IsString | IsUntyped, "untyped string"},
            UntypedNil:     {UntypedNil, IsUntyped, "untyped nil"},
        }

        func AssertableTo

        func AssertableTo(V *Interface, T Type) bool

        AssertableTo reports whether a value of type V can be asserted to have type T.

        The behavior of AssertableTo is unspecified in three cases:

        • if T is Typ[Invalid]
        • if V is a generalized interface; i.e., an interface that may only be used as a type constraint in Go code
        • if T is an uninstantiated generic type

        func AssignableTo

        func AssignableTo(V, T Type) bool

        AssignableTo reports whether a value of type V is assignable to a variable of type T.

        The behavior of AssignableTo is unspecified if V or T is Typ[Invalid] or an uninstantiated generic type.

        func CheckExpr

        func CheckExpr(fset *token.FileSet, pkg *Package, pos token.Pos, expr ast.Expr, info *Info) (err error)

        CheckExpr type checks the expression expr as if it had appeared at position pos of package pkg. Type information about the expression is recorded in info. The expression may be an identifier denoting an uninstantiated generic function or type.

        If pkg == nil, the Universe scope is used and the provided position pos is ignored. If pkg != nil, and pos is invalid, the package scope is used. Otherwise, pos must belong to the package.

        An error is returned if pos is not within the package or if the node cannot be type-checked.

        Note: Eval and CheckExpr should not be used instead of running Check to compute types and values, but in addition to Check, as these functions ignore the context in which an expression is used (e.g., an assignment). Thus, top-level untyped constants will return an untyped type rather than the respective context-specific type.

        func Comparable

        func Comparable(T Type) bool

        Comparable reports whether values of type T are comparable.

        func ConvertibleTo

        func ConvertibleTo(V, T Type) bool

        ConvertibleTo reports whether a value of type V is convertible to a value of type T.

        The behavior of ConvertibleTo is unspecified if V or T is Typ[Invalid] or an uninstantiated generic type.

        func DefPredeclaredTestFuncs

        func DefPredeclaredTestFuncs()

        DefPredeclaredTestFuncs defines the assert and trace built-ins. These built-ins are intended for debugging and testing of this package only.

        func ExprString

        func ExprString(x ast.Expr) string

        ExprString returns the (possibly shortened) string representation for x. Shortened representations are suitable for user interfaces but may not necessarily follow Go syntax.

        func Id

        func Id(pkg *Package, name string) string

        Id returns name if it is exported, otherwise it returns the name qualified with the package path.

        func Identical

        func Identical(x, y Type) bool

        Identical reports whether x and y are identical types. Receivers of Signature types are ignored.

        func IdenticalIgnoreTags

        func IdenticalIgnoreTags(x, y Type) bool

        IdenticalIgnoreTags reports whether x and y are identical types if tags are ignored. Receivers of Signature types are ignored.

        func Implements

        func Implements(V Type, T *Interface) bool

        Implements reports whether type V implements interface T.

        The behavior of Implements is unspecified if V is Typ[Invalid] or an uninstantiated generic type.

        func IsInterface

        func IsInterface(t Type) bool

        IsInterface reports whether t is an interface type.

        func ObjectString

        func ObjectString(obj Object, qf Qualifier) string

        ObjectString returns the string form of obj. The Qualifier controls the printing of package-level objects, and may be nil.

        func Satisfies

        func Satisfies(V Type, T *Interface) bool

        Satisfies reports whether type V satisfies the constraint T.

        The behavior of Satisfies is unspecified if V is Typ[Invalid] or an uninstantiated generic type.

        func SelectionString

        func SelectionString(s *Selection, qf Qualifier) string

        SelectionString returns the string form of s. The Qualifier controls the printing of package-level objects, and may be nil.

        Examples:

        "field (T) f int"
        "method (T) f(X) Y"
        "method expr (T) f(X) Y"
        

        func TypeString

        func TypeString(typ Type, qf Qualifier) string

        TypeString returns the string representation of typ. The Qualifier controls the printing of package-level objects, and may be nil.

        func WriteExpr

        func WriteExpr(buf *bytes.Buffer, x ast.Expr)

        WriteExpr writes the (possibly shortened) string representation for x to buf. Shortened representations are suitable for user interfaces but may not necessarily follow Go syntax.

        func WriteSignature

        func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier)

        WriteSignature writes the representation of the signature sig to buf, without a leading "func" keyword. The Qualifier controls the printing of package-level objects, and may be nil.

        func WriteType

        func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier)

        WriteType writes the string representation of typ to buf. The Qualifier controls the printing of package-level objects, and may be nil.

        type Alias

        An Alias represents an alias type. Whether or not Alias types are created is controlled by the gotypesalias setting with the GODEBUG environment variable. For gotypesalias=1, alias declarations produce an Alias type. Otherwise, the alias information is only in the type name, which points directly to the actual (aliased) type.

        type Alias struct {
            // contains filtered or unexported fields
        }
        

        func NewAlias

        func NewAlias(obj *TypeName, rhs Type) *Alias

        NewAlias creates a new Alias type with the given type name and rhs. rhs must not be nil.

        func (*Alias) Obj

        func (a *Alias) Obj() *TypeName

        func (*Alias) String

        func (a *Alias) String() string

        func (*Alias) Underlying

        func (a *Alias) Underlying() Type

        type ArgumentError

        An ArgumentError holds an error associated with an argument index.

        type ArgumentError struct {
            Index int
            Err   error
        }
        

        func (*ArgumentError) Error

        func (e *ArgumentError) Error() string

        func (*ArgumentError) Unwrap

        func (e *ArgumentError) Unwrap() error

        type Array

        An Array represents an array type.

        type Array struct {
            // contains filtered or unexported fields
        }
        

        func NewArray

        func NewArray(elem Type, len int64) *Array

        NewArray returns a new array type for the given element type and length. A negative length indicates an unknown length.

        func (*Array) Elem

        func (a *Array) Elem() Type

        Elem returns element type of array a.

        func (*Array) Len

        func (a *Array) Len() int64

        Len returns the length of array a. A negative result indicates an unknown length.

        func (*Array) String

        func (a *Array) String() string

        func (*Array) Underlying

        func (a *Array) Underlying() Type

        type Basic

        A Basic represents a basic type.

        type Basic struct {
            // contains filtered or unexported fields
        }
        

        func (*Basic) Info

        func (b *Basic) Info() BasicInfo

        Info returns information about properties of basic type b.

        func (*Basic) Kind

        func (b *Basic) Kind() BasicKind

        Kind returns the kind of basic type b.

        func (*Basic) Name

        func (b *Basic) Name() string

        Name returns the name of basic type b.

        func (*Basic) String

        func (b *Basic) String() string

        func (*Basic) Underlying

        func (b *Basic) Underlying() Type

        type BasicInfo

        BasicInfo is a set of flags describing properties of a basic type.

        type BasicInfo int

        Properties of basic types.

        const (
            IsBoolean BasicInfo = 1 << iota
            IsInteger
            IsUnsigned
            IsFloat
            IsComplex
            IsString
            IsUntyped
        
            IsOrdered   = IsInteger | IsFloat | IsString
            IsNumeric   = IsInteger | IsFloat | IsComplex
            IsConstType = IsBoolean | IsNumeric | IsString
        )

        type BasicKind

        BasicKind describes the kind of basic type.

        type BasicKind int
        const (
            Invalid BasicKind = iota // type is invalid
        
            // predeclared types
            Bool
            Int
            Int8
            Int16
            Int32
            Int64
            Uint
            Uint8
            Uint16
            Uint32
            Uint64
            Uintptr
            Float32
            Float64
            Complex64
            Complex128
            String
            UnsafePointer
        
            // types for untyped values
            UntypedBool
            UntypedInt
            UntypedRune
            UntypedFloat
            UntypedComplex
            UntypedString
            UntypedNil
        
            // aliases
            Byte = Uint8
            Rune = Int32
        )

        type Builtin

        A Builtin represents a built-in function. Builtins don't have a valid type.

        type Builtin struct {
            // contains filtered or unexported fields
        }
        

        func (*Builtin) Exported

        func (obj *Builtin) Exported() bool

        Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

        func (*Builtin) Id

        func (obj *Builtin) Id() string

        Id is a wrapper for Id(obj.Pkg(), obj.Name()).

        func (*Builtin) Name

        func (obj *Builtin) Name() string

        Name returns the object's (package-local, unqualified) name.

        func (*Builtin) Parent

        func (obj *Builtin) Parent() *Scope

        Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

        func (*Builtin) Pkg

        func (obj *Builtin) Pkg() *Package

        Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

        func (*Builtin) Pos

        func (obj *Builtin) Pos() token.Pos

        Pos returns the declaration position of the object's identifier.

        func (*Builtin) String

        func (obj *Builtin) String() string

        func (*Builtin) Type

        func (obj *Builtin) Type() Type

        Type returns the object's type.

        type Chan

        A Chan represents a channel type.

        type Chan struct {
            // contains filtered or unexported fields
        }
        

        func NewChan

        func NewChan(dir ChanDir, elem Type) *Chan

        NewChan returns a new channel type for the given direction and element type.

        func (*Chan) Dir

        func (c *Chan) Dir() ChanDir

        Dir returns the direction of channel c.

        func (*Chan) Elem

        func (c *Chan) Elem() Type

        Elem returns the element type of channel c.

        func (*Chan) String

        func (c *Chan) String() string

        func (*Chan) Underlying

        func (c *Chan) Underlying() Type

        type ChanDir

        A ChanDir value indicates a channel direction.

        type ChanDir int

        The direction of a channel is indicated by one of these constants.

        const (
            SendRecv ChanDir = iota
            SendOnly
            RecvOnly
        )

        type Checker

        A Checker maintains the state of the type checker. It must be created with NewChecker.

        type Checker struct {
            *Info
            // contains filtered or unexported fields
        }
        

        func NewChecker

        func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker

        NewChecker returns a new Checker instance for a given package. Package files may be added incrementally via checker.Files.

        func (*Checker) Files

        func (check *Checker) Files(files []*ast.File) error

        Files checks the provided files as part of the checker's package.

        type Config

        A Config specifies the configuration for type checking. The zero value for Config is a ready-to-use default configuration.

        type Config struct {
            // Context is the context used for resolving global identifiers. If nil, the
            // type checker will initialize this field with a newly created context.
            Context *Context
        
            // GoVersion describes the accepted Go language version. The string must
            // start with a prefix of the form "go%d.%d" (e.g. "go1.20", "go1.21rc1", or
            // "go1.21.0") or it must be empty; an empty string disables Go language
            // version checks. If the format is invalid, invoking the type checker will
            // result in an error.
            GoVersion string
        
            // If IgnoreFuncBodies is set, function bodies are not
            // type-checked.
            IgnoreFuncBodies bool
        
            // If FakeImportC is set, `import "C"` (for packages requiring Cgo)
            // declares an empty "C" package and errors are omitted for qualified
            // identifiers referring to package C (which won't find an object).
            // This feature is intended for the standard library cmd/api tool.
            //
            // Caution: Effects may be unpredictable due to follow-on errors.
            //          Do not use casually!
            FakeImportC bool
        
            // If Error != nil, it is called with each error found
            // during type checking; err has dynamic type Error.
            // Secondary errors (for instance, to enumerate all types
            // involved in an invalid recursive type declaration) have
            // error strings that start with a '\t' character.
            // If Error == nil, type-checking stops with the first
            // error found.
            Error func(err error)
        
            // An importer is used to import packages referred to from
            // import declarations.
            // If the installed importer implements ImporterFrom, the type
            // checker calls ImportFrom instead of Import.
            // The type checker reports an error if an importer is needed
            // but none was installed.
            Importer Importer
        
            // If Sizes != nil, it provides the sizing functions for package unsafe.
            // Otherwise SizesFor("gc", "amd64") is used instead.
            Sizes Sizes
        
            // If DisableUnusedImportCheck is set, packages are not checked
            // for unused imports.
            DisableUnusedImportCheck bool
            // contains filtered or unexported fields
        }
        

        func (*Config) Check

        func (conf *Config) Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error)

        Check type-checks a package and returns the resulting package object and the first error if any. Additionally, if info != nil, Check populates each of the non-nil maps in the Info struct.

        The package is marked as complete if no errors occurred, otherwise it is incomplete. See [Config.Error] for controlling behavior in the presence of errors.

        The package is specified by a list of *ast.Files and corresponding file set, and the package path the package is identified with. The clean path must not be empty or dot (".").

        type Const

        A Const represents a declared constant.

        type Const struct {
            // contains filtered or unexported fields
        }
        

        func NewConst

        func NewConst(pos token.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const

        NewConst returns a new constant with value val. The remaining arguments set the attributes found with all Objects.

        func (*Const) Exported

        func (obj *Const) Exported() bool

        Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

        func (*Const) Id

        func (obj *Const) Id() string

        Id is a wrapper for Id(obj.Pkg(), obj.Name()).

        func (*Const) Name

        func (obj *Const) Name() string

        Name returns the object's (package-local, unqualified) name.

        func (*Const) Parent

        func (obj *Const) Parent() *Scope

        Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

        func (*Const) Pkg

        func (obj *Const) Pkg() *Package

        Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

        func (*Const) Pos

        func (obj *Const) Pos() token.Pos

        Pos returns the declaration position of the object's identifier.

        func (*Const) String

        func (obj *Const) String() string

        func (*Const) Type

        func (obj *Const) Type() Type

        Type returns the object's type.

        func (*Const) Val

        func (obj *Const) Val() constant.Value

        Val returns the constant's value.

        type Context

        A Context is an opaque type checking context. It may be used to share identical type instances across type-checked packages or calls to Instantiate. Contexts are safe for concurrent use.

        The use of a shared context does not guarantee that identical instances are deduplicated in all cases.

        type Context struct {
            // contains filtered or unexported fields
        }
        

        func NewContext

        func NewContext() *Context

        NewContext creates a new Context.

        type Error

        An Error describes a type-checking error; it implements the error interface. A "soft" error is an error that still permits a valid interpretation of a package (such as "unused variable"); "hard" errors may lead to unpredictable behavior if ignored.

        type Error struct {
            Fset *token.FileSet // file set for interpretation of Pos
            Pos  token.Pos      // error position
            Msg  string         // error message
            Soft bool           // if set, error is "soft"
            // contains filtered or unexported fields
        }
        

        func (Error) Error

        func (err Error) Error() string

        Error returns an error string formatted as follows: filename:line:column: message

        type Func

        A Func represents a declared function, concrete method, or abstract (interface) method. Its Type() is always a *Signature. An abstract method may belong to many interfaces due to embedding.

        type Func struct {
            // contains filtered or unexported fields
        }
        

        func MissingMethod

        func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool)

        MissingMethod returns (nil, false) if V implements T, otherwise it returns a missing method required by T and whether it is missing or just has the wrong type: either a pointer receiver or wrong signature.

        For non-interface types V, or if static is set, V implements T if all methods of T are present in V. Otherwise (V is an interface and static is not set), MissingMethod only checks that methods of T which are also present in V have matching types (e.g., for a type assertion x.(T) where x is of interface type V).

        func NewFunc

        func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func

        NewFunc returns a new function with the given signature, representing the function's type.

        func (*Func) Exported

        func (obj *Func) Exported() bool

        Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

        func (*Func) FullName

        func (obj *Func) FullName() string

        FullName returns the package- or receiver-type-qualified name of function or method obj.

        func (*Func) Id

        func (obj *Func) Id() string

        Id is a wrapper for Id(obj.Pkg(), obj.Name()).

        func (*Func) Name

        func (obj *Func) Name() string

        Name returns the object's (package-local, unqualified) name.

        func (*Func) Origin

        func (obj *Func) Origin() *Func

        Origin returns the canonical Func for its receiver, i.e. the Func object recorded in Info.Defs.

        For synthetic functions created during instantiation (such as methods on an instantiated Named type or interface methods that depend on type arguments), this will be the corresponding Func on the generic (uninstantiated) type. For all other Funcs Origin returns the receiver.

        func (*Func) Parent

        func (obj *Func) Parent() *Scope

        Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

        func (*Func) Pkg

        func (obj *Func) Pkg() *Package

        Pkg returns the package to which the function belongs.

        The result is nil for methods of types in the Universe scope, like method Error of the error built-in interface type.

        func (*Func) Pos

        func (obj *Func) Pos() token.Pos

        Pos returns the declaration position of the object's identifier.

        func (*Func) Scope

        func (obj *Func) Scope() *Scope

        Scope returns the scope of the function's body block. The result is nil for imported or instantiated functions and methods (but there is also no mechanism to get to an instantiated function).

        func (*Func) String

        func (obj *Func) String() string

        func (*Func) Type

        func (obj *Func) Type() Type

        Type returns the object's type.

        type ImportMode

        ImportMode is reserved for future use.

        type ImportMode int

        type Importer

        An Importer resolves import paths to Packages.

        CAUTION: This interface does not support the import of locally vendored packages. See https://golang.org/s/go15vendor. If possible, external implementations should implement ImporterFrom.

        type Importer interface {
            // Import returns the imported package for the given import path.
            // The semantics is like for ImporterFrom.ImportFrom except that
            // dir and mode are ignored (since they are not present).
            Import(path string) (*Package, error)
        }

        type ImporterFrom

        An ImporterFrom resolves import paths to packages; it supports vendoring per https://golang.org/s/go15vendor. Use go/importer to obtain an ImporterFrom implementation.

        type ImporterFrom interface {
            // Importer is present for backward-compatibility. Calling
            // Import(path) is the same as calling ImportFrom(path, "", 0);
            // i.e., locally vendored packages may not be found.
            // The types package does not call Import if an ImporterFrom
            // is present.
            Importer
        
            // ImportFrom returns the imported package for the given import
            // path when imported by a package file located in dir.
            // If the import failed, besides returning an error, ImportFrom
            // is encouraged to cache and return a package anyway, if one
            // was created. This will reduce package inconsistencies and
            // follow-on type checker errors due to the missing package.
            // The mode value must be 0; it is reserved for future use.
            // Two calls to ImportFrom with the same path and dir must
            // return the same package.
            ImportFrom(path, dir string, mode ImportMode) (*Package, error)
        }

        type Info

        Info holds result type information for a type-checked package. Only the information for which a map is provided is collected. If the package has type errors, the collected information may be incomplete.

        type Info struct {
            // Types maps expressions to their types, and for constant
            // expressions, also their values. Invalid expressions are
            // omitted.
            //
            // For (possibly parenthesized) identifiers denoting built-in
            // functions, the recorded signatures are call-site specific:
            // if the call result is not a constant, the recorded type is
            // an argument-specific signature. Otherwise, the recorded type
            // is invalid.
            //
            // The Types map does not record the type of every identifier,
            // only those that appear where an arbitrary expression is
            // permitted. For instance, the identifier f in a selector
            // expression x.f is found only in the Selections map, the
            // identifier z in a variable declaration 'var z int' is found
            // only in the Defs map, and identifiers denoting packages in
            // qualified identifiers are collected in the Uses map.
            Types map[ast.Expr]TypeAndValue
        
            // Instances maps identifiers denoting generic types or functions to their
            // type arguments and instantiated type.
            //
            // For example, Instances will map the identifier for 'T' in the type
            // instantiation T[int, string] to the type arguments [int, string] and
            // resulting instantiated *Named type. Given a generic function
            // func F[A any](A), Instances will map the identifier for 'F' in the call
            // expression F(int(1)) to the inferred type arguments [int], and resulting
            // instantiated *Signature.
            //
            // Invariant: Instantiating Uses[id].Type() with Instances[id].TypeArgs
            // results in an equivalent of Instances[id].Type.
            Instances map[*ast.Ident]Instance
        
            // Defs maps identifiers to the objects they define (including
            // package names, dots "." of dot-imports, and blank "_" identifiers).
            // For identifiers that do not denote objects (e.g., the package name
            // in package clauses, or symbolic variables t in t := x.(type) of
            // type switch headers), the corresponding objects are nil.
            //
            // For an embedded field, Defs returns the field *Var it defines.
            //
            // Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos()
            Defs map[*ast.Ident]Object
        
            // Uses maps identifiers to the objects they denote.
            //
            // For an embedded field, Uses returns the *TypeName it denotes.
            //
            // Invariant: Uses[id].Pos() != id.Pos()
            Uses map[*ast.Ident]Object
        
            // Implicits maps nodes to their implicitly declared objects, if any.
            // The following node and object types may appear:
            //
            //     node               declared object
            //
            //     *ast.ImportSpec    *PkgName for imports without renames
            //     *ast.CaseClause    type-specific *Var for each type switch case clause (incl. default)
            //     *ast.Field         anonymous parameter *Var (incl. unnamed results)
            //
            Implicits map[ast.Node]Object
        
            // Selections maps selector expressions (excluding qualified identifiers)
            // to their corresponding selections.
            Selections map[*ast.SelectorExpr]*Selection
        
            // Scopes maps ast.Nodes to the scopes they define. Package scopes are not
            // associated with a specific node but with all files belonging to a package.
            // Thus, the package scope can be found in the type-checked Package object.
            // Scopes nest, with the Universe scope being the outermost scope, enclosing
            // the package scope, which contains (one or more) files scopes, which enclose
            // function scopes which in turn enclose statement and function literal scopes.
            // Note that even though package-level functions are declared in the package
            // scope, the function scopes are embedded in the file scope of the file
            // containing the function declaration.
            //
            // The Scope of a function contains the declarations of any
            // type parameters, parameters, and named results, plus any
            // local declarations in the body block.
            // It is coextensive with the complete extent of the
            // function's syntax ([*ast.FuncDecl] or [*ast.FuncLit]).
            // The Scopes mapping does not contain an entry for the
            // function body ([*ast.BlockStmt]); the function's scope is
            // associated with the [*ast.FuncType].
            //
            // The following node types may appear in Scopes:
            //
            //     *ast.File
            //     *ast.FuncType
            //     *ast.TypeSpec
            //     *ast.BlockStmt
            //     *ast.IfStmt
            //     *ast.SwitchStmt
            //     *ast.TypeSwitchStmt
            //     *ast.CaseClause
            //     *ast.CommClause
            //     *ast.ForStmt
            //     *ast.RangeStmt
            //
            Scopes map[ast.Node]*Scope
        
            // InitOrder is the list of package-level initializers in the order in which
            // they must be executed. Initializers referring to variables related by an
            // initialization dependency appear in topological order, the others appear
            // in source order. Variables without an initialization expression do not
            // appear in this list.
            InitOrder []*Initializer
        
            // FileVersions maps a file to its Go version string.
            // If the file doesn't specify a version, the reported
            // string is Config.GoVersion.
            // Version strings begin with “go”, like “go1.21”, and
            // are suitable for use with the [go/version] package.
            FileVersions map[*ast.File]string
        }
        

        Example

        ExampleInfo prints various facts recorded by the type checker in a types.Info struct: definitions of and references to each named object, and the type, value, and mode of every expression in the package.

        Code:

        // Parse a single source file.
        const input = `
        package fib
        
        type S string
        
        var a, b, c = len(b), S(c), "hello"
        
        func fib(x int) int {
            if x < 2 {
                return x
            }
            return fib(x-1) - fib(x-2)
        }`
        // We need a specific fileset in this test below for positions.
        // Cannot use typecheck helper.
        fset := token.NewFileSet()
        f := mustParse(fset, input)
        
        // Type-check the package.
        // We create an empty map for each kind of input
        // we're interested in, and Check populates them.
        info := types.Info{
            Types: make(map[ast.Expr]types.TypeAndValue),
            Defs:  make(map[*ast.Ident]types.Object),
            Uses:  make(map[*ast.Ident]types.Object),
        }
        var conf types.Config
        pkg, err := conf.Check("fib", fset, []*ast.File{f}, &info)
        if err != nil {
            log.Fatal(err)
        }
        
        // Print package-level variables in initialization order.
        fmt.Printf("InitOrder: %v\n\n", info.InitOrder)
        
        // For each named object, print the line and
        // column of its definition and each of its uses.
        fmt.Println("Defs and Uses of each named object:")
        usesByObj := make(map[types.Object][]string)
        for id, obj := range info.Uses {
            posn := fset.Position(id.Pos())
            lineCol := fmt.Sprintf("%d:%d", posn.Line, posn.Column)
            usesByObj[obj] = append(usesByObj[obj], lineCol)
        }
        var items []string
        for obj, uses := range usesByObj {
            sort.Strings(uses)
            item := fmt.Sprintf("%s:\n  defined at %s\n  used at %s",
                types.ObjectString(obj, types.RelativeTo(pkg)),
                fset.Position(obj.Pos()),
                strings.Join(uses, ", "))
            items = append(items, item)
        }
        sort.Strings(items) // sort by line:col, in effect
        fmt.Println(strings.Join(items, "\n"))
        fmt.Println()
        
        fmt.Println("Types and Values of each expression:")
        items = nil
        for expr, tv := range info.Types {
            var buf strings.Builder
            posn := fset.Position(expr.Pos())
            tvstr := tv.Type.String()
            if tv.Value != nil {
                tvstr += " = " + tv.Value.String()
            }
            // line:col | expr | mode : type = value
            fmt.Fprintf(&buf, "%2d:%2d | %-19s | %-7s : %s",
                posn.Line, posn.Column, exprString(fset, expr),
                mode(tv), tvstr)
            items = append(items, buf.String())
        }
        sort.Strings(items)
        fmt.Println(strings.Join(items, "\n"))
        
        

        Output:

        InitOrder: [c = "hello" b = S(c) a = len(b)]
        
        Defs and Uses of each named object:
        builtin len:
          defined at -
          used at 6:15
        func fib(x int) int:
          defined at fib:8:6
          used at 12:20, 12:9
        type S string:
          defined at fib:4:6
          used at 6:23
        type int:
          defined at -
          used at 8:12, 8:17
        type string:
          defined at -
          used at 4:8
        var b S:
          defined at fib:6:8
          used at 6:19
        var c string:
          defined at fib:6:11
          used at 6:25
        var x int:
          defined at fib:8:10
          used at 10:10, 12:13, 12:24, 9:5
        
        Types and Values of each expression:
         4: 8 | string              | type    : string
         6:15 | len                 | builtin : func(fib.S) int
         6:15 | len(b)              | value   : int
         6:19 | b                   | var     : fib.S
         6:23 | S                   | type    : fib.S
         6:23 | S(c)                | value   : fib.S
         6:25 | c                   | var     : string
         6:29 | "hello"             | value   : string = "hello"
         8:12 | int                 | type    : int
         8:17 | int                 | type    : int
         9: 5 | x                   | var     : int
         9: 5 | x < 2               | value   : untyped bool
         9: 9 | 2                   | value   : int = 2
        10:10 | x                   | var     : int
        12: 9 | fib                 | value   : func(x int) int
        12: 9 | fib(x - 1)          | value   : int
        12: 9 | fib(x-1) - fib(x-2) | value   : int
        12:13 | x                   | var     : int
        12:13 | x - 1               | value   : int
        12:15 | 1                   | value   : int = 1
        12:20 | fib                 | value   : func(x int) int
        12:20 | fib(x - 2)          | value   : int
        12:24 | x                   | var     : int
        12:24 | x - 2               | value   : int
        12:26 | 2                   | value   : int = 2
        

        func (*Info) ObjectOf

        func (info *Info) ObjectOf(id *ast.Ident) Object

        ObjectOf returns the object denoted by the specified id, or nil if not found.

        If id is an embedded struct field, Info.ObjectOf returns the field (*Var) it defines, not the type (*TypeName) it uses.

        Precondition: the Uses and Defs maps are populated.

        func (*Info) PkgNameOf

        func (info *Info) PkgNameOf(imp *ast.ImportSpec) *PkgName

        PkgNameOf returns the local package name defined by the import, or nil if not found.

        For dot-imports, the package name is ".".

        Precondition: the Defs and Implicts maps are populated.

        func (*Info) TypeOf

        func (info *Info) TypeOf(e ast.Expr) Type

        TypeOf returns the type of expression e, or nil if not found. Precondition: the Types, Uses and Defs maps are populated.

        type Initializer

        An Initializer describes a package-level variable, or a list of variables in case of a multi-valued initialization expression, and the corresponding initialization expression.

        type Initializer struct {
            Lhs []*Var // var Lhs = Rhs
            Rhs ast.Expr
        }
        

        func (*Initializer) String

        func (init *Initializer) String() string

        type Instance

        Instance reports the type arguments and instantiated type for type and function instantiations. For type instantiations, Type will be of dynamic type *Named. For function instantiations, Type will be of dynamic type *Signature.

        type Instance struct {
            TypeArgs *TypeList
            Type     Type
        }
        

        type Interface

        An Interface represents an interface type.

        type Interface struct {
            // contains filtered or unexported fields
        }
        

        func NewInterface

        func NewInterface(methods []*Func, embeddeds []*Named) *Interface

        NewInterface returns a new interface for the given methods and embedded types. NewInterface takes ownership of the provided methods and may modify their types by setting missing receivers.

        Deprecated: Use NewInterfaceType instead which allows arbitrary embedded types.

        func NewInterfaceType

        func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface

        NewInterfaceType returns a new interface for the given methods and embedded types. NewInterfaceType takes ownership of the provided methods and may modify their types by setting missing receivers.

        To avoid race conditions, the interface's type set should be computed before concurrent use of the interface, by explicitly calling Complete.

        func (*Interface) Complete

        func (t *Interface) Complete() *Interface

        Complete computes the interface's type set. It must be called by users of NewInterfaceType and NewInterface after the interface's embedded types are fully defined and before using the interface type in any way other than to form other types. The interface must not contain duplicate methods or a panic occurs. Complete returns the receiver.

        Interface types that have been completed are safe for concurrent use.

        func (*Interface) Embedded

        func (t *Interface) Embedded(i int) *Named

        Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds(). The result is nil if the i'th embedded type is not a defined type.

        Deprecated: Use Interface.EmbeddedType which is not restricted to defined (*Named) types.

        func (*Interface) EmbeddedType

        func (t *Interface) EmbeddedType(i int) Type

        EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().

        func (*Interface) Empty

        func (t *Interface) Empty() bool

        Empty reports whether t is the empty interface.

        func (*Interface) ExplicitMethod

        func (t *Interface) ExplicitMethod(i int) *Func

        ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods(). The methods are ordered by their unique Id.

        func (*Interface) IsComparable

        func (t *Interface) IsComparable() bool

        IsComparable reports whether each type in interface t's type set is comparable.

        func (*Interface) IsImplicit

        func (t *Interface) IsImplicit() bool

        IsImplicit reports whether the interface t is a wrapper for a type set literal.

        func (*Interface) IsMethodSet

        func (t *Interface) IsMethodSet() bool

        IsMethodSet reports whether the interface t is fully described by its method set.

        func (*Interface) MarkImplicit

        func (t *Interface) MarkImplicit()

        MarkImplicit marks the interface t as implicit, meaning this interface corresponds to a constraint literal such as ~T or A|B without explicit interface embedding. MarkImplicit should be called before any concurrent use of implicit interfaces.

        func (*Interface) Method

        func (t *Interface) Method(i int) *Func

        Method returns the i'th method of interface t for 0 <= i < t.NumMethods(). The methods are ordered by their unique Id.

        func (*Interface) NumEmbeddeds

        func (t *Interface) NumEmbeddeds() int

        NumEmbeddeds returns the number of embedded types in interface t.

        func (*Interface) NumExplicitMethods

        func (t *Interface) NumExplicitMethods() int

        NumExplicitMethods returns the number of explicitly declared methods of interface t.

        func (*Interface) NumMethods

        func (t *Interface) NumMethods() int

        NumMethods returns the total number of methods of interface t.

        func (*Interface) String

        func (t *Interface) String() string

        func (*Interface) Underlying

        func (t *Interface) Underlying() Type

        type Label

        A Label represents a declared label. Labels don't have a type.

        type Label struct {
            // contains filtered or unexported fields
        }
        

        func NewLabel

        func NewLabel(pos token.Pos, pkg *Package, name string) *Label

        NewLabel returns a new label.

        func (*Label) Exported

        func (obj *Label) Exported() bool

        Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

        func (*Label) Id

        func (obj *Label) Id() string

        Id is a wrapper for Id(obj.Pkg(), obj.Name()).

        func (*Label) Name

        func (obj *Label) Name() string

        Name returns the object's (package-local, unqualified) name.

        func (*Label) Parent

        func (obj *Label) Parent() *Scope

        Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

        func (*Label) Pkg

        func (obj *Label) Pkg() *Package

        Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

        func (*Label) Pos

        func (obj *Label) Pos() token.Pos

        Pos returns the declaration position of the object's identifier.

        func (*Label) String

        func (obj *Label) String() string

        func (*Label) Type

        func (obj *Label) Type() Type

        Type returns the object's type.

        type Map

        A Map represents a map type.

        type Map struct {
            // contains filtered or unexported fields
        }
        

        func NewMap

        func NewMap(key, elem Type) *Map

        NewMap returns a new map for the given key and element types.

        func (*Map) Elem

        func (m *Map) Elem() Type

        Elem returns the element type of map m.

        func (*Map) Key

        func (m *Map) Key() Type

        Key returns the key type of map m.

        func (*Map) String

        func (t *Map) String() string

        func (*Map) Underlying

        func (t *Map) Underlying() Type

        type MethodSet

        A MethodSet is an ordered set of concrete or abstract (interface) methods; a method is a MethodVal selection, and they are ordered by ascending m.Obj().Id(). The zero value for a MethodSet is a ready-to-use empty method set.

        type MethodSet struct {
            // contains filtered or unexported fields
        }
        

        Example

        ExampleMethodSet prints the method sets of various types.

        Code:

        // Parse a single source file.
        const input = `
        package temperature
        import "fmt"
        type Celsius float64
        func (c Celsius) String() string  { return fmt.Sprintf("%g°C", c) }
        func (c *Celsius) SetF(f float64) { *c = Celsius(f - 32 / 9 * 5) }
        
        type S struct { I; m int }
        type I interface { m() byte }
        `
        fset := token.NewFileSet()
        f, err := parser.ParseFile(fset, "celsius.go", input, 0)
        if err != nil {
            log.Fatal(err)
        }
        
        // Type-check a package consisting of this file.
        // Type information for the imported packages
        // comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
        conf := types.Config{Importer: importer.Default()}
        pkg, err := conf.Check("temperature", fset, []*ast.File{f}, nil)
        if err != nil {
            log.Fatal(err)
        }
        
        // Print the method sets of Celsius and *Celsius.
        celsius := pkg.Scope().Lookup("Celsius").Type()
        for _, t := range []types.Type{celsius, types.NewPointer(celsius)} {
            fmt.Printf("Method set of %s:\n", t)
            mset := types.NewMethodSet(t)
            for i := 0; i < mset.Len(); i++ {
                fmt.Println(mset.At(i))
            }
            fmt.Println()
        }
        
        // Print the method set of S.
        styp := pkg.Scope().Lookup("S").Type()
        fmt.Printf("Method set of %s:\n", styp)
        fmt.Println(types.NewMethodSet(styp))
        
        

        Output:

        Method set of temperature.Celsius:
        method (temperature.Celsius) String() string
        
        Method set of *temperature.Celsius:
        method (*temperature.Celsius) SetF(f float64)
        method (*temperature.Celsius) String() string
        
        Method set of temperature.S:
        MethodSet {}
        

        func NewMethodSet

        func NewMethodSet(T Type) *MethodSet

        NewMethodSet returns the method set for the given type T. It always returns a non-nil method set, even if it is empty.

        func (*MethodSet) At

        func (s *MethodSet) At(i int) *Selection

        At returns the i'th method in s for 0 <= i < s.Len().

        func (*MethodSet) Len

        func (s *MethodSet) Len() int

        Len returns the number of methods in s.

        func (*MethodSet) Lookup

        func (s *MethodSet) Lookup(pkg *Package, name string) *Selection

        Lookup returns the method with matching package and name, or nil if not found.

        func (*MethodSet) String

        func (s *MethodSet) String() string

        type Named

        A Named represents a named (defined) type.

        type Named struct {
            // contains filtered or unexported fields
        }
        

        func NewNamed

        func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named

        NewNamed returns a new named type for the given type name, underlying type, and associated methods. If the given type name obj doesn't have a type yet, its type is set to the returned named type. The underlying type must not be a *Named.

        func (*Named) AddMethod

        func (t *Named) AddMethod(m *Func)

        AddMethod adds method m unless it is already in the method list. t must not have type arguments.

        func (*Named) Method

        func (t *Named) Method(i int) *Func

        Method returns the i'th method of named type t for 0 <= i < t.NumMethods().

        For an ordinary or instantiated type t, the receiver base type of this method is the named type t. For an uninstantiated generic type t, each method receiver is instantiated with its receiver type parameters.

        func (*Named) NumMethods

        func (t *Named) NumMethods() int

        NumMethods returns the number of explicit methods defined for t.

        func (*Named) Obj

        func (t *Named) Obj() *TypeName

        Obj returns the type name for the declaration defining the named type t. For instantiated types, this is same as the type name of the origin type.

        func (*Named) Origin

        func (t *Named) Origin() *Named

        Origin returns the generic type from which the named type t is instantiated. If t is not an instantiated type, the result is t.

        func (*Named) SetTypeParams

        func (t *Named) SetTypeParams(tparams []*TypeParam)

        SetTypeParams sets the type parameters of the named type t. t must not have type arguments.

        func (*Named) SetUnderlying

        func (t *Named) SetUnderlying(underlying Type)

        SetUnderlying sets the underlying type and marks t as complete. t must not have type arguments.

        func (*Named) String

        func (t *Named) String() string

        func (*Named) TypeArgs

        func (t *Named) TypeArgs() *TypeList

        TypeArgs returns the type arguments used to instantiate the named type t.

        func (*Named) TypeParams

        func (t *Named) TypeParams() *TypeParamList

        TypeParams returns the type parameters of the named type t, or nil. The result is non-nil for an (originally) generic type even if it is instantiated.

        func (*Named) Underlying

        func (t *Named) Underlying() Type

        TODO(gri) Investigate if Unalias can be moved to where underlying is set.

        type Nil

        Nil represents the predeclared value nil.

        type Nil struct {
            // contains filtered or unexported fields
        }
        

        func (*Nil) Exported

        func (obj *Nil) Exported() bool

        Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

        func (*Nil) Id

        func (obj *Nil) Id() string

        Id is a wrapper for Id(obj.Pkg(), obj.Name()).

        func (*Nil) Name

        func (obj *Nil) Name() string

        Name returns the object's (package-local, unqualified) name.

        func (*Nil) Parent

        func (obj *Nil) Parent() *Scope

        Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

        func (*Nil) Pkg

        func (obj *Nil) Pkg() *Package

        Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

        func (*Nil) Pos

        func (obj *Nil) Pos() token.Pos

        Pos returns the declaration position of the object's identifier.

        func (*Nil) String

        func (obj *Nil) String() string

        func (*Nil) Type

        func (obj *Nil) Type() Type

        Type returns the object's type.

        type Object

        An Object describes a named language entity such as a package, constant, type, variable, function (incl. methods), or label. All objects implement the Object interface.

        type Object interface {
            Parent() *Scope // scope in which this object is declared; nil for methods and struct fields
            Pos() token.Pos // position of object identifier in declaration
            Pkg() *Package  // package to which this object belongs; nil for labels and objects in the Universe scope
            Name() string   // package local object name
            Type() Type     // object type
            Exported() bool // reports whether the name starts with a capital letter
            Id() string     // object name if exported, qualified name if not exported (see func Id)
        
            // String returns a human-readable string of the object.
            String() string
            // contains filtered or unexported methods
        }

        func LookupFieldOrMethod

        func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool)

        LookupFieldOrMethod looks up a field or method with given package and name in T and returns the corresponding *Var or *Func, an index sequence, and a bool indicating if there were any pointer indirections on the path to the field or method. If addressable is set, T is the type of an addressable variable (only matters for method lookups). T must not be nil.

        The last index entry is the field or method index in the (possibly embedded) type where the entry was found, either:

        1. the list of declared methods of a named type; or
        2. the list of all methods (method set) of an interface type; or
        3. the list of fields of a struct type.

        The earlier index entries are the indices of the embedded struct fields traversed to get to the found entry, starting at depth 0.

        If no entry is found, a nil object is returned. In this case, the returned index and indirect values have the following meaning:

        • If index != nil, the index sequence points to an ambiguous entry (the same name appeared more than once at the same embedding level).

        • If indirect is set, a method with a pointer receiver type was found but there was no pointer on the path from the actual receiver type to the method's formal receiver base type, nor was the receiver addressable.

        type Package

        A Package describes a Go package.

        type Package struct {
            // contains filtered or unexported fields
        }
        

        The Unsafe package is the package returned by an importer for the import path "unsafe".

        var Unsafe *Package

        func NewPackage

        func NewPackage(path, name string) *Package

        NewPackage returns a new Package for the given package path and name. The package is not complete and contains no explicit imports.

        func (*Package) Complete

        func (pkg *Package) Complete() bool

        A package is complete if its scope contains (at least) all exported objects; otherwise it is incomplete.

        func (*Package) GoVersion

        func (pkg *Package) GoVersion() string

        GoVersion returns the minimum Go version required by this package. If the minimum version is unknown, GoVersion returns the empty string. Individual source files may specify a different minimum Go version, as reported in the go/ast.File.GoVersion field.

        func (*Package) Imports

        func (pkg *Package) Imports() []*Package

        Imports returns the list of packages directly imported by pkg; the list is in source order.

        If pkg was loaded from export data, Imports includes packages that provide package-level objects referenced by pkg. This may be more or less than the set of packages directly imported by pkg's source code.

        If pkg uses cgo and the FakeImportC configuration option was enabled, the imports list may contain a fake "C" package.

        func (*Package) MarkComplete

        func (pkg *Package) MarkComplete()

        MarkComplete marks a package as complete.

        func (*Package) Name

        func (pkg *Package) Name() string

        Name returns the package name.

        func (*Package) Path

        func (pkg *Package) Path() string

        Path returns the package path.

        func (*Package) Scope

        func (pkg *Package) Scope() *Scope

        Scope returns the (complete or incomplete) package scope holding the objects declared at package level (TypeNames, Consts, Vars, and Funcs). For a nil pkg receiver, Scope returns the Universe scope.

        func (*Package) SetImports

        func (pkg *Package) SetImports(list []*Package)

        SetImports sets the list of explicitly imported packages to list. It is the caller's responsibility to make sure list elements are unique.

        func (*Package) SetName

        func (pkg *Package) SetName(name string)

        SetName sets the package name.

        func (*Package) String

        func (pkg *Package) String() string

        type PkgName

        A PkgName represents an imported Go package. PkgNames don't have a type.

        type PkgName struct {
            // contains filtered or unexported fields
        }
        

        func NewPkgName

        func NewPkgName(pos token.Pos, pkg *Package, name string, imported *Package) *PkgName

        NewPkgName returns a new PkgName object representing an imported package. The remaining arguments set the attributes found with all Objects.

        func (*PkgName) Exported

        func (obj *PkgName) Exported() bool

        Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

        func (*PkgName) Id

        func (obj *PkgName) Id() string

        Id is a wrapper for Id(obj.Pkg(), obj.Name()).

        func (*PkgName) Imported

        func (obj *PkgName) Imported() *Package

        Imported returns the package that was imported. It is distinct from Pkg(), which is the package containing the import statement.

        func (*PkgName) Name

        func (obj *PkgName) Name() string

        Name returns the object's (package-local, unqualified) name.

        func (*PkgName) Parent

        func (obj *PkgName) Parent() *Scope

        Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

        func (*PkgName) Pkg

        func (obj *PkgName) Pkg() *Package

        Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

        func (*PkgName) Pos

        func (obj *PkgName) Pos() token.Pos

        Pos returns the declaration position of the object's identifier.

        func (*PkgName) String

        func (obj *PkgName) String() string

        func (*PkgName) Type

        func (obj *PkgName) Type() Type

        Type returns the object's type.

        type Pointer

        A Pointer represents a pointer type.

        type Pointer struct {
            // contains filtered or unexported fields
        }
        

        func NewPointer

        func NewPointer(elem Type) *Pointer

        NewPointer returns a new pointer type for the given element (base) type.

        func (*Pointer) Elem

        func (p *Pointer) Elem() Type

        Elem returns the element type for the given pointer p.

        func (*Pointer) String

        func (p *Pointer) String() string

        func (*Pointer) Underlying

        func (p *Pointer) Underlying() Type

        type Qualifier

        A Qualifier controls how named package-level objects are printed in calls to TypeString, ObjectString, and SelectionString.

        These three formatting routines call the Qualifier for each package-level object O, and if the Qualifier returns a non-empty string p, the object is printed in the form p.O. If it returns an empty string, only the object name O is printed.

        Using a nil Qualifier is equivalent to using (*Package).Path: the object is qualified by the import path, e.g., "encoding/json.Marshal".

        type Qualifier func(*Package) string

        func RelativeTo

        func RelativeTo(pkg *Package) Qualifier

        RelativeTo returns a Qualifier that fully qualifies members of all packages other than pkg.

        type Scope

        A Scope maintains a set of objects and links to its containing (parent) and contained (children) scopes. Objects may be inserted and looked up by name. The zero value for Scope is a ready-to-use empty scope.

        type Scope struct {
            // contains filtered or unexported fields
        }
        

        The Universe scope contains all predeclared objects of Go. It is the outermost scope of any chain of nested scopes.

        var Universe *Scope

        Example

        ExampleScope prints the tree of Scopes of a package created from a set of parsed files.

        Code:

        // Parse the source files for a package.
        fset := token.NewFileSet()
        var files []*ast.File
        for _, src := range []string{
            `package main
        import "fmt"
        func main() {
            freezing := FToC(-18)
            fmt.Println(freezing, Boiling) }
        `,
            `package main
        import "fmt"
        type Celsius float64
        func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
        func FToC(f float64) Celsius { return Celsius(f - 32 / 9 * 5) }
        const Boiling Celsius = 100
        func Unused() { {}; {{ var x int; _ = x }} } // make sure empty block scopes get printed
        `,
        } {
            files = append(files, mustParse(fset, src))
        }
        
        // Type-check a package consisting of these files.
        // Type information for the imported "fmt" package
        // comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
        conf := types.Config{Importer: importer.Default()}
        pkg, err := conf.Check("temperature", fset, files, nil)
        if err != nil {
            log.Fatal(err)
        }
        
        // Print the tree of scopes.
        // For determinism, we redact addresses.
        var buf strings.Builder
        pkg.Scope().WriteTo(&buf, 0, true)
        rx := regexp.MustCompile(` 0x[a-fA-F\d]*`)
        fmt.Println(rx.ReplaceAllString(buf.String(), ""))
        
        

        Output:

        package "temperature" scope {
        .  const temperature.Boiling temperature.Celsius
        .  type temperature.Celsius float64
        .  func temperature.FToC(f float64) temperature.Celsius
        .  func temperature.Unused()
        .  func temperature.main()
        .  main scope {
        .  .  package fmt
        .  .  function scope {
        .  .  .  var freezing temperature.Celsius
        .  .  }
        .  }
        .  main scope {
        .  .  package fmt
        .  .  function scope {
        .  .  .  var c temperature.Celsius
        .  .  }
        .  .  function scope {
        .  .  .  var f float64
        .  .  }
        .  .  function scope {
        .  .  .  block scope {
        .  .  .  }
        .  .  .  block scope {
        .  .  .  .  block scope {
        .  .  .  .  .  var x int
        .  .  .  .  }
        .  .  .  }
        .  .  }
        .  }
        }
        

        func NewScope

        func NewScope(parent *Scope, pos, end token.Pos, comment string) *Scope

        NewScope returns a new, empty scope contained in the given parent scope, if any. The comment is for debugging only.

        func (*Scope) Child

        func (s *Scope) Child(i int) *Scope

        Child returns the i'th child scope for 0 <= i < NumChildren().

        func (*Scope) Contains

        func (s *Scope) Contains(pos token.Pos) bool

        Contains reports whether pos is within the scope's extent. The result is guaranteed to be valid only if the type-checked AST has complete position information.

        func (*Scope) End

        func (s *Scope) End() token.Pos

        func (*Scope) Innermost

        func (s *Scope) Innermost(pos token.Pos) *Scope

        Innermost returns the innermost (child) scope containing pos. If pos is not within any scope, the result is nil. The result is also nil for the Universe scope. The result is guaranteed to be valid only if the type-checked AST has complete position information.

        func (*Scope) Insert

        func (s *Scope) Insert(obj Object) Object

        Insert attempts to insert an object obj into scope s. If s already contains an alternative object alt with the same name, Insert leaves s unchanged and returns alt. Otherwise it inserts obj, sets the object's parent scope if not already set, and returns nil.

        func (*Scope) Len

        func (s *Scope) Len() int

        Len returns the number of scope elements.

        func (*Scope) Lookup

        func (s *Scope) Lookup(name string) Object

        Lookup returns the object in scope s with the given name if such an object exists; otherwise the result is nil.

        func (*Scope) LookupParent

        func (s *Scope) LookupParent(name string, pos token.Pos) (*Scope, Object)

        LookupParent follows the parent chain of scopes starting with s until it finds a scope where Lookup(name) returns a non-nil object, and then returns that scope and object. If a valid position pos is provided, only objects that were declared at or before pos are considered. If no such scope and object exists, the result is (nil, nil).

        Note that obj.Parent() may be different from the returned scope if the object was inserted into the scope and already had a parent at that time (see Insert). This can only happen for dot-imported objects whose scope is the scope of the package that exported them.

        func (*Scope) Names

        func (s *Scope) Names() []string

        Names returns the scope's element names in sorted order.

        func (*Scope) NumChildren

        func (s *Scope) NumChildren() int

        NumChildren returns the number of scopes nested in s.

        func (*Scope) Parent

        func (s *Scope) Parent() *Scope

        Parent returns the scope's containing (parent) scope.

        func (*Scope) Pos

        func (s *Scope) Pos() token.Pos

        Pos and End describe the scope's source code extent [pos, end). The results are guaranteed to be valid only if the type-checked AST has complete position information. The extent is undefined for Universe and package scopes.

        func (*Scope) String

        func (s *Scope) String() string

        String returns a string representation of the scope, for debugging.

        func (*Scope) WriteTo

        func (s *Scope) WriteTo(w io.Writer, n int, recurse bool)

        WriteTo writes a string representation of the scope to w, with the scope elements sorted by name. The level of indentation is controlled by n >= 0, with n == 0 for no indentation. If recurse is set, it also writes nested (children) scopes.

        type Selection

        A Selection describes a selector expression x.f. For the declarations:

        type T struct{ x int; E }
        type E struct{}
        func (e E) m() {}
        var p *T
        

        the following relations exist:

        Selector    Kind          Recv    Obj    Type       Index     Indirect
        
        p.x         FieldVal      T       x      int        {0}       true
        p.m         MethodVal     *T      m      func()     {1, 0}    true
        T.m         MethodExpr    T       m      func(T)    {1, 0}    false
        
        type Selection struct {
            // contains filtered or unexported fields
        }
        

        func (*Selection) Index

        func (s *Selection) Index() []int

        Index describes the path from x to f in x.f. The last index entry is the field or method index of the type declaring f; either:

        1. the list of declared methods of a named type; or
        2. the list of methods of an interface type; or
        3. the list of fields of a struct type.

        The earlier index entries are the indices of the embedded fields implicitly traversed to get from (the type of) x to f, starting at embedding depth 0.

        func (*Selection) Indirect

        func (s *Selection) Indirect() bool

        Indirect reports whether any pointer indirection was required to get from x to f in x.f.

        Beware: Indirect spuriously returns true (Go issue #8353) for a MethodVal selection in which the receiver argument and parameter both have type *T so there is no indirection. Unfortunately, a fix is too risky.

        func (*Selection) Kind

        func (s *Selection) Kind() SelectionKind

        Kind returns the selection kind.

        func (*Selection) Obj

        func (s *Selection) Obj() Object

        Obj returns the object denoted by x.f; a *Var for a field selection, and a *Func in all other cases.

        func (*Selection) Recv

        func (s *Selection) Recv() Type

        Recv returns the type of x in x.f.

        func (*Selection) String

        func (s *Selection) String() string

        func (*Selection) Type

        func (s *Selection) Type() Type

        Type returns the type of x.f, which may be different from the type of f. See Selection for more information.

        type SelectionKind

        SelectionKind describes the kind of a selector expression x.f (excluding qualified identifiers).

        If x is a struct or *struct, a selector expression x.f may denote a sequence of selection operations x.a.b.c.f. The SelectionKind describes the kind of the final (explicit) operation; all the previous (implicit) operations are always field selections. Each element of Indices specifies an implicit field (a, b, c) by its index in the struct type of the field selection operand.

        For a FieldVal operation, the final selection refers to the field specified by Selection.Obj.

        For a MethodVal operation, the final selection refers to a method. If the "pointerness" of the method's declared receiver does not match that of the effective receiver after implicit field selection, then an & or * operation is implicitly applied to the receiver variable or value. So, x.f denotes (&x.a.b.c).f when f requires a pointer receiver but x.a.b.c is a non-pointer variable; and it denotes (*x.a.b.c).f when f requires a non-pointer receiver but x.a.b.c is a pointer value.

        All pointer indirections, whether due to implicit or explicit field selections or * operations inserted for "pointerness", panic if applied to a nil pointer, so a method call x.f() may panic even before the function call.

        By contrast, a MethodExpr operation T.f is essentially equivalent to a function literal of the form:

        func(x T, args) (results) { return x.f(args) }
        

        Consequently, any implicit field selections and * operations inserted for "pointerness" are not evaluated until the function is called, so a T.f or (*T).f expression never panics.

        type SelectionKind int
        const (
            FieldVal   SelectionKind = iota // x.f is a struct field selector
            MethodVal                       // x.f is a method selector
            MethodExpr                      // x.f is a method expression
        )

        type Signature

        A Signature represents a (non-builtin) function or method type. The receiver is ignored when comparing signatures for identity.

        type Signature struct {
            // contains filtered or unexported fields
        }
        

        func NewSignature

        func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature

        NewSignature returns a new function type for the given receiver, parameters, and results, either of which may be nil. If variadic is set, the function is variadic, it must have at least one parameter, and the last parameter must be of unnamed slice type.

        Deprecated: Use NewSignatureType instead which allows for type parameters.

        func NewSignatureType

        func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature

        NewSignatureType creates a new function type for the given receiver, receiver type parameters, type parameters, parameters, and results. If variadic is set, params must hold at least one parameter and the last parameter's core type must be of unnamed slice or bytestring type. If recv is non-nil, typeParams must be empty. If recvTypeParams is non-empty, recv must be non-nil.

        func (*Signature) Params

        func (s *Signature) Params() *Tuple

        Params returns the parameters of signature s, or nil.

        func (*Signature) Recv

        func (s *Signature) Recv() *Var

        Recv returns the receiver of signature s (if a method), or nil if a function. It is ignored when comparing signatures for identity.

        For an abstract method, Recv returns the enclosing interface either as a *Named or an *Interface. Due to embedding, an interface may contain methods whose receiver type is a different interface.

        func (*Signature) RecvTypeParams

        func (s *Signature) RecvTypeParams() *TypeParamList

        RecvTypeParams returns the receiver type parameters of signature s, or nil.

        func (*Signature) Results

        func (s *Signature) Results() *Tuple

        Results returns the results of signature s, or nil.

        func (*Signature) String

        func (t *Signature) String() string

        func (*Signature) TypeParams

        func (s *Signature) TypeParams() *TypeParamList

        TypeParams returns the type parameters of signature s, or nil.

        func (*Signature) Underlying

        func (t *Signature) Underlying() Type

        func (*Signature) Variadic

        func (s *Signature) Variadic() bool

        Variadic reports whether the signature s is variadic.

        type Sizes

        Sizes defines the sizing functions for package unsafe.

        type Sizes interface {
            // Alignof returns the alignment of a variable of type T.
            // Alignof must implement the alignment guarantees required by the spec.
            // The result must be >= 1.
            Alignof(T Type) int64
        
            // Offsetsof returns the offsets of the given struct fields, in bytes.
            // Offsetsof must implement the offset guarantees required by the spec.
            // A negative entry in the result indicates that the struct is too large.
            Offsetsof(fields []*Var) []int64
        
            // Sizeof returns the size of a variable of type T.
            // Sizeof must implement the size guarantees required by the spec.
            // A negative result indicates that T is too large.
            Sizeof(T Type) int64
        }

        func SizesFor

        func SizesFor(compiler, arch string) Sizes

        SizesFor returns the Sizes used by a compiler for an architecture. The result is nil if a compiler/architecture pair is not known.

        Supported architectures for compiler "gc": "386", "amd64", "amd64p32", "arm", "arm64", "loong64", "mips", "mipsle", "mips64", "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", "sparc64", "wasm".

        type Slice

        A Slice represents a slice type.

        type Slice struct {
            // contains filtered or unexported fields
        }
        

        func NewSlice

        func NewSlice(elem Type) *Slice

        NewSlice returns a new slice type for the given element type.

        func (*Slice) Elem

        func (s *Slice) Elem() Type

        Elem returns the element type of slice s.

        func (*Slice) String

        func (s *Slice) String() string

        func (*Slice) Underlying

        func (s *Slice) Underlying() Type

        type StdSizes

        StdSizes is a convenience type for creating commonly used Sizes. It makes the following simplifying assumptions:

        • The size of explicitly sized basic types (int16, etc.) is the specified size.
        • The size of strings and interfaces is 2*WordSize.
        • The size of slices is 3*WordSize.
        • The size of an array of n elements corresponds to the size of a struct of n consecutive fields of the array's element type.
        • The size of a struct is the offset of the last field plus that field's size. As with all element types, if the struct is used in an array its size must first be aligned to a multiple of the struct's alignment.
        • All other types have size WordSize.
        • Arrays and structs are aligned per spec definition; all other types are naturally aligned with a maximum alignment MaxAlign.

        *StdSizes implements Sizes.

        type StdSizes struct {
            WordSize int64 // word size in bytes - must be >= 4 (32bits)
            MaxAlign int64 // maximum alignment in bytes - must be >= 1
        }
        

        func (*StdSizes) Alignof

        func (s *StdSizes) Alignof(T Type) (result int64)

        func (*StdSizes) Offsetsof

        func (s *StdSizes) Offsetsof(fields []*Var) []int64

        func (*StdSizes) Sizeof

        func (s *StdSizes) Sizeof(T Type) int64

        type Struct

        A Struct represents a struct type.

        type Struct struct {
            // contains filtered or unexported fields
        }
        

        func NewStruct

        func NewStruct(fields []*Var, tags []string) *Struct

        NewStruct returns a new struct with the given fields and corresponding field tags. If a field with index i has a tag, tags[i] must be that tag, but len(tags) may be only as long as required to hold the tag with the largest index i. Consequently, if no field has a tag, tags may be nil.

        func (*Struct) Field

        func (s *Struct) Field(i int) *Var

        Field returns the i'th field for 0 <= i < NumFields().

        func (*Struct) NumFields

        func (s *Struct) NumFields() int

        NumFields returns the number of fields in the struct (including blank and embedded fields).

        func (*Struct) String

        func (t *Struct) String() string

        func (*Struct) Tag

        func (s *Struct) Tag(i int) string

        Tag returns the i'th field tag for 0 <= i < NumFields().

        func (*Struct) Underlying

        func (t *Struct) Underlying() Type

        type Term

        A Term represents a term in a Union.

        type Term term

        func NewTerm

        func NewTerm(tilde bool, typ Type) *Term

        NewTerm returns a new union term.

        func (*Term) String

        func (t *Term) String() string

        func (*Term) Tilde

        func (t *Term) Tilde() bool

        func (*Term) Type

        func (t *Term) Type() Type

        type Tuple

        A Tuple represents an ordered list of variables; a nil *Tuple is a valid (empty) tuple. Tuples are used as components of signatures and to represent the type of multiple assignments; they are not first class types of Go.

        type Tuple struct {
            // contains filtered or unexported fields
        }
        

        func NewTuple

        func NewTuple(x ...*Var) *Tuple

        NewTuple returns a new tuple for the given variables.

        func (*Tuple) At

        func (t *Tuple) At(i int) *Var

        At returns the i'th variable of tuple t.

        func (*Tuple) Len

        func (t *Tuple) Len() int

        Len returns the number variables of tuple t.

        func (*Tuple) String

        func (t *Tuple) String() string

        func (*Tuple) Underlying

        func (t *Tuple) Underlying() Type

        type Type

        A Type represents a type of Go. All types implement the Type interface.

        type Type interface {
            // Underlying returns the underlying type of a type.
            Underlying() Type
        
            // String returns a string representation of a type.
            String() string
        }

        func Default

        func Default(t Type) Type

        Default returns the default "typed" type for an "untyped" type; it returns the incoming type for all other types. The default type for untyped nil is untyped nil.

        func Instantiate

        func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error)

        Instantiate instantiates the type orig with the given type arguments targs. orig must be a *Named or a *Signature type. If there is no error, the resulting Type is an instantiated type of the same kind (either a *Named or a *Signature). Methods attached to a *Named type are also instantiated, and associated with a new *Func that has the same position as the original method, but nil function scope.

        If ctxt is non-nil, it may be used to de-duplicate the instance against previous instances with the same identity. As a special case, generic *Signature origin types are only considered identical if they are pointer equivalent, so that instantiating distinct (but possibly identical) signatures will yield different instances. The use of a shared context does not guarantee that identical instances are deduplicated in all cases.

        If validate is set, Instantiate verifies that the number of type arguments and parameters match, and that the type arguments satisfy their corresponding type constraints. If verification fails, the resulting error may wrap an *ArgumentError indicating which type argument did not satisfy its corresponding type parameter constraint, and why.

        If validate is not set, Instantiate does not verify the type argument count or whether the type arguments satisfy their constraints. Instantiate is guaranteed to not return an error, but may panic. Specifically, for *Signature types, Instantiate will panic immediately if the type argument count is incorrect; for *Named types, a panic may occur later inside the *Named API.

        func Unalias

        func Unalias(t Type) Type

        Unalias returns t if it is not an alias type; otherwise it follows t's alias chain until it reaches a non-alias type which is then returned. Consequently, the result is never an alias type.

        type TypeAndValue

        TypeAndValue reports the type and value (for constants) of the corresponding expression.

        type TypeAndValue struct {
            Type  Type
            Value constant.Value
            // contains filtered or unexported fields
        }
        

        func Eval

        func Eval(fset *token.FileSet, pkg *Package, pos token.Pos, expr string) (_ TypeAndValue, err error)

        Eval returns the type and, if constant, the value for the expression expr, evaluated at position pos of package pkg, which must have been derived from type-checking an AST with complete position information relative to the provided file set.

        The meaning of the parameters fset, pkg, and pos is the same as in CheckExpr. An error is returned if expr cannot be parsed successfully, or the resulting expr AST cannot be type-checked.

        func (TypeAndValue) Addressable

        func (tv TypeAndValue) Addressable() bool

        Addressable reports whether the corresponding expression is addressable (https://golang.org/ref/spec#Address_operators).

        func (TypeAndValue) Assignable

        func (tv TypeAndValue) Assignable() bool

        Assignable reports whether the corresponding expression is assignable to (provided a value of the right type).

        func (TypeAndValue) HasOk

        func (tv TypeAndValue) HasOk() bool

        HasOk reports whether the corresponding expression may be used on the rhs of a comma-ok assignment.

        func (TypeAndValue) IsBuiltin

        func (tv TypeAndValue) IsBuiltin() bool

        IsBuiltin reports whether the corresponding expression denotes a (possibly parenthesized) built-in function.

        func (TypeAndValue) IsNil

        func (tv TypeAndValue) IsNil() bool

        IsNil reports whether the corresponding expression denotes the predeclared value nil.

        func (TypeAndValue) IsType

        func (tv TypeAndValue) IsType() bool

        IsType reports whether the corresponding expression specifies a type.

        func (TypeAndValue) IsValue

        func (tv TypeAndValue) IsValue() bool

        IsValue reports whether the corresponding expression is a value. Builtins are not considered values. Constant values have a non- nil Value.

        func (TypeAndValue) IsVoid

        func (tv TypeAndValue) IsVoid() bool

        IsVoid reports whether the corresponding expression is a function call without results.

        type TypeList

        TypeList holds a list of types.

        type TypeList struct {
            // contains filtered or unexported fields
        }
        

        func (*TypeList) At

        func (l *TypeList) At(i int) Type

        At returns the i'th type in the list.

        func (*TypeList) Len

        func (l *TypeList) Len() int

        Len returns the number of types in the list. It is safe to call on a nil receiver.

        type TypeName

        A TypeName represents a name for a (defined or alias) type.

        type TypeName struct {
            // contains filtered or unexported fields
        }
        

        func NewTypeName

        func NewTypeName(pos token.Pos, pkg *Package, name string, typ Type) *TypeName

        NewTypeName returns a new type name denoting the given typ. The remaining arguments set the attributes found with all Objects.

        The typ argument may be a defined (Named) type or an alias type. It may also be nil such that the returned TypeName can be used as argument for NewNamed, which will set the TypeName's type as a side- effect.

        func (*TypeName) Exported

        func (obj *TypeName) Exported() bool

        Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

        func (*TypeName) Id

        func (obj *TypeName) Id() string

        Id is a wrapper for Id(obj.Pkg(), obj.Name()).

        func (*TypeName) IsAlias

        func (obj *TypeName) IsAlias() bool

        IsAlias reports whether obj is an alias name for a type.

        func (*TypeName) Name

        func (obj *TypeName) Name() string

        Name returns the object's (package-local, unqualified) name.

        func (*TypeName) Parent

        func (obj *TypeName) Parent() *Scope

        Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

        func (*TypeName) Pkg

        func (obj *TypeName) Pkg() *Package

        Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

        func (*TypeName) Pos

        func (obj *TypeName) Pos() token.Pos

        Pos returns the declaration position of the object's identifier.

        func (*TypeName) String

        func (obj *TypeName) String() string

        func (*TypeName) Type

        func (obj *TypeName) Type() Type

        Type returns the object's type.

        type TypeParam

        A TypeParam represents a type parameter type.

        type TypeParam struct {
            // contains filtered or unexported fields
        }
        

        func NewTypeParam

        func NewTypeParam(obj *TypeName, constraint Type) *TypeParam

        NewTypeParam returns a new TypeParam. Type parameters may be set on a Named or Signature type by calling SetTypeParams. Setting a type parameter on more than one type will result in a panic.

        The constraint argument can be nil, and set later via SetConstraint. If the constraint is non-nil, it must be fully defined.

        func (*TypeParam) Constraint

        func (t *TypeParam) Constraint() Type

        Constraint returns the type constraint specified for t.

        func (*TypeParam) Index

        func (t *TypeParam) Index() int

        Index returns the index of the type param within its param list, or -1 if the type parameter has not yet been bound to a type.

        func (*TypeParam) Obj

        func (t *TypeParam) Obj() *TypeName

        Obj returns the type name for the type parameter t.

        func (*TypeParam) SetConstraint

        func (t *TypeParam) SetConstraint(bound Type)

        SetConstraint sets the type constraint for t.

        It must be called by users of NewTypeParam after the bound's underlying is fully defined, and before using the type parameter in any way other than to form other types. Once SetConstraint returns the receiver, t is safe for concurrent use.

        func (*TypeParam) String

        func (t *TypeParam) String() string

        func (*TypeParam) Underlying

        func (t *TypeParam) Underlying() Type

        type TypeParamList

        TypeParamList holds a list of type parameters.

        type TypeParamList struct {
            // contains filtered or unexported fields
        }
        

        func (*TypeParamList) At

        func (l *TypeParamList) At(i int) *TypeParam

        At returns the i'th type parameter in the list.

        func (*TypeParamList) Len

        func (l *TypeParamList) Len() int

        Len returns the number of type parameters in the list. It is safe to call on a nil receiver.

        type Union

        A Union represents a union of terms embedded in an interface.

        type Union struct {
            // contains filtered or unexported fields
        }
        

        func NewUnion

        func NewUnion(terms []*Term) *Union

        NewUnion returns a new Union type with the given terms. It is an error to create an empty union; they are syntactically not possible.

        func (*Union) Len

        func (u *Union) Len() int

        func (*Union) String

        func (u *Union) String() string

        func (*Union) Term

        func (u *Union) Term(i int) *Term

        func (*Union) Underlying

        func (u *Union) Underlying() Type

        type Var

        A Variable represents a declared variable (including function parameters and results, and struct fields).

        type Var struct {
            // contains filtered or unexported fields
        }
        

        func NewField

        func NewField(pos token.Pos, pkg *Package, name string, typ Type, embedded bool) *Var

        NewField returns a new variable representing a struct field. For embedded fields, the name is the unqualified type name under which the field is accessible.

        func NewParam

        func NewParam(pos token.Pos, pkg *Package, name string, typ Type) *Var

        NewParam returns a new variable representing a function parameter.

        func NewVar

        func NewVar(pos token.Pos, pkg *Package, name string, typ Type) *Var

        NewVar returns a new variable. The arguments set the attributes found with all Objects.

        func (*Var) Anonymous

        func (obj *Var) Anonymous() bool

        Anonymous reports whether the variable is an embedded field. Same as Embedded; only present for backward-compatibility.

        func (*Var) Embedded

        func (obj *Var) Embedded() bool

        Embedded reports whether the variable is an embedded field.

        func (*Var) Exported

        func (obj *Var) Exported() bool

        Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

        func (*Var) Id

        func (obj *Var) Id() string

        Id is a wrapper for Id(obj.Pkg(), obj.Name()).

        func (*Var) IsField

        func (obj *Var) IsField() bool

        IsField reports whether the variable is a struct field.

        func (*Var) Name

        func (obj *Var) Name() string

        Name returns the object's (package-local, unqualified) name.

        func (*Var) Origin

        func (obj *Var) Origin() *Var

        Origin returns the canonical Var for its receiver, i.e. the Var object recorded in Info.Defs.

        For synthetic Vars created during instantiation (such as struct fields or function parameters that depend on type arguments), this will be the corresponding Var on the generic (uninstantiated) type. For all other Vars Origin returns the receiver.

        func (*Var) Parent

        func (obj *Var) Parent() *Scope

        Parent returns the scope in which the object is declared. The result is nil for methods and struct fields.

        func (*Var) Pkg

        func (obj *Var) Pkg() *Package

        Pkg returns the package to which the object belongs. The result is nil for labels and objects in the Universe scope.

        func (*Var) Pos

        func (obj *Var) Pos() token.Pos

        Pos returns the declaration position of the object's identifier.

        func (*Var) String

        func (obj *Var) String() string

        func (*Var) Type

        func (obj *Var) Type() Type

        Type returns the object's type.

        version - Go Documentation Server
        ...

        Package version

        import "go/version"
        Overview
        Index

        Overview ▾

        Package version provides operations on Go versions in Go toolchain name syntax: strings like "go1.20", "go1.21.0", "go1.22rc2", and "go1.23.4-bigcorp".

        func Compare

        func Compare(x, y string) int

        Compare returns -1, 0, or +1 depending on whether x < y, x == y, or x > y, interpreted as Go versions. The versions x and y must begin with a "go" prefix: "go1.21" not "1.21". Invalid versions, including the empty string, compare less than valid versions and equal to each other. The language version "go1.21" compares less than the release candidate and eventual releases "go1.21rc1" and "go1.21.0".

        func IsValid

        func IsValid(x string) bool

        IsValid reports whether the version x is valid.

        func Lang

        func Lang(x string) string

        Lang returns the Go language version for version x. If x is not a valid version, Lang returns the empty string. For example:

        Lang("go1.21rc2") = "go1.21"
        Lang("go1.21.2") = "go1.21"
        Lang("go1.21") = "go1.21"
        Lang("go1") = "go1"
        Lang("bad") = ""
        Lang("1.21") = ""
        
        goberkeley - Go Documentation Server
        ...

        Command goberkeley

        Subdirectories

        Name Synopsis
        ..
        berkeley
        hash - Go Documentation Server
        ...

        Package hash

        Overview ▾

        Package hash provides interfaces for hash functions.

        Example (BinaryMarshaler)

        Code:

        const (
            input1 = "The tunneling gopher digs downwards, "
            input2 = "unaware of what he will find."
        )
        
        first := sha256.New()
        first.Write([]byte(input1))
        
        marshaler, ok := first.(encoding.BinaryMarshaler)
        if !ok {
            log.Fatal("first does not implement encoding.BinaryMarshaler")
        }
        state, err := marshaler.MarshalBinary()
        if err != nil {
            log.Fatal("unable to marshal hash:", err)
        }
        
        second := sha256.New()
        
        unmarshaler, ok := second.(encoding.BinaryUnmarshaler)
        if !ok {
            log.Fatal("second does not implement encoding.BinaryUnmarshaler")
        }
        if err := unmarshaler.UnmarshalBinary(state); err != nil {
            log.Fatal("unable to unmarshal hash:", err)
        }
        
        first.Write([]byte(input2))
        second.Write([]byte(input2))
        
        fmt.Printf("%x\n", first.Sum(nil))
        fmt.Println(bytes.Equal(first.Sum(nil), second.Sum(nil)))
        

        Output:

        57d51a066f3a39942649cd9a76c77e97ceab246756ff3888659e6aa5a07f4a52
        true
        

        Index ▾

        Examples

        Package (BinaryMarshaler)

        Package files

        hash.go

        type Hash

        Hash is the common interface implemented by all hash functions.

        Hash implementations in the standard library (e.g. hash/crc32 and crypto/sha256) implement the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler interfaces. Marshaling a hash implementation allows its internal state to be saved and used for additional processing later, without having to re-write the data previously written to the hash. The hash state may contain portions of the input in its original form, which users are expected to handle for any possible security implications.

        Compatibility: Any future changes to hash or crypto packages will endeavor to maintain compatibility with state encoded using previous versions. That is, any released versions of the packages should be able to decode data written with any previously released version, subject to issues such as security fixes. See the Go compatibility document for background: https://golang.org/doc/go1compat

        type Hash interface {
            // Write (via the embedded io.Writer interface) adds more data to the running hash.
            // It never returns an error.
            io.Writer
        
            // Sum appends the current hash to b and returns the resulting slice.
            // It does not change the underlying hash state.
            Sum(b []byte) []byte
        
            // Reset resets the Hash to its initial state.
            Reset()
        
            // Size returns the number of bytes Sum will return.
            Size() int
        
            // BlockSize returns the hash's underlying block size.
            // The Write method must be able to accept any amount
            // of data, but it may operate more efficiently if all writes
            // are a multiple of the block size.
            BlockSize() int
        }

        type Hash32

        Hash32 is the common interface implemented by all 32-bit hash functions.

        type Hash32 interface {
            Hash
            Sum32() uint32
        }

        type Hash64

        Hash64 is the common interface implemented by all 64-bit hash functions.

        type Hash64 interface {
            Hash
            Sum64() uint64
        }

        Subdirectories

        Name Synopsis
        ..
        adler32 Package adler32 implements the Adler-32 checksum.
        crc32 Package crc32 implements the 32-bit cyclic redundancy check, or CRC-32, checksum.
        crc64 Package crc64 implements the 64-bit cyclic redundancy check, or CRC-64, checksum.
        fnv Package fnv implements FNV-1 and FNV-1a, non-cryptographic hash functions created by Glenn Fowler, Landon Curt Noll, and Phong Vo.
        maphash Package maphash provides hash functions on byte sequences.
        adler32 - Go Documentation Server
        ...

        Package adler32

        import "hash/adler32"
        Overview
        Index

        Overview ▾

        Package adler32 implements the Adler-32 checksum.

        It is defined in RFC 1950:

        Adler-32 is composed of two sums accumulated per byte: s1 is
        the sum of all bytes, s2 is the sum of all s1 values. Both sums
        are done modulo 65521. s1 is initialized to 1, s2 to zero.  The
        Adler-32 checksum is stored as s2*65536 + s1 in most-
        significant-byte first (network) order.
        

        Constants

        The size of an Adler-32 checksum in bytes.

        const Size = 4

        func Checksum

        func Checksum(data []byte) uint32

        Checksum returns the Adler-32 checksum of data.

        func New

        func New() hash.Hash32

        New returns a new hash.Hash32 computing the Adler-32 checksum. Its Sum method will lay the value out in big-endian byte order. The returned Hash32 also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

        crc32 - Go Documentation Server
        ...

        Package crc32

        import "hash/crc32"
        Overview
        Index
        Examples

        Overview ▾

        Package crc32 implements the 32-bit cyclic redundancy check, or CRC-32, checksum. See https://en.wikipedia.org/wiki/Cyclic_redundancy_check for information.

        Polynomials are represented in LSB-first form also known as reversed representation.

        See https://en.wikipedia.org/wiki/Mathematics_of_cyclic_redundancy_checks#Reversed_representations_and_reciprocal_polynomials for information.

        Constants

        Predefined polynomials.

        const (
            // IEEE is by far and away the most common CRC-32 polynomial.
            // Used by ethernet (IEEE 802.3), v.42, fddi, gzip, zip, png, ...
            IEEE = 0xedb88320
        
            // Castagnoli's polynomial, used in iSCSI.
            // Has better error detection characteristics than IEEE.
            // https://dx.doi.org/10.1109/26.231911
            Castagnoli = 0x82f63b78
        
            // Koopman's polynomial.
            // Also has better error detection characteristics than IEEE.
            // https://dx.doi.org/10.1109/DSN.2002.1028931
            Koopman = 0xeb31d82e
        )

        The size of a CRC-32 checksum in bytes.

        const Size = 4

        Variables

        IEEETable is the table for the IEEE polynomial.

        var IEEETable = simpleMakeTable(IEEE)

        func Checksum

        func Checksum(data []byte, tab *Table) uint32

        Checksum returns the CRC-32 checksum of data using the polynomial represented by the Table.

        func ChecksumIEEE

        func ChecksumIEEE(data []byte) uint32

        ChecksumIEEE returns the CRC-32 checksum of data using the IEEE polynomial.

        func New

        func New(tab *Table) hash.Hash32

        New creates a new hash.Hash32 computing the CRC-32 checksum using the polynomial represented by the Table. Its Sum method will lay the value out in big-endian byte order. The returned Hash32 also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

        func NewIEEE

        func NewIEEE() hash.Hash32

        NewIEEE creates a new hash.Hash32 computing the CRC-32 checksum using the IEEE polynomial. Its Sum method will lay the value out in big-endian byte order. The returned Hash32 also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

        func Update

        func Update(crc uint32, tab *Table, p []byte) uint32

        Update returns the result of adding the bytes in p to the crc.

        type Table

        Table is a 256-word table representing the polynomial for efficient processing.

        type Table [256]uint32

        func MakeTable

        func MakeTable(poly uint32) *Table

        MakeTable returns a Table constructed from the specified polynomial. The contents of this Table must not be modified.

        Example

        Code:

        // In this package, the CRC polynomial is represented in reversed notation,
        // or LSB-first representation.
        //
        // LSB-first representation is a hexadecimal number with n bits, in which the
        // most significant bit represents the coefficient of x⁰ and the least significant
        // bit represents the coefficient of xⁿ⁻¹ (the coefficient for xⁿ is implicit).
        //
        // For example, CRC32-Q, as defined by the following polynomial,
        //	x³²+ x³¹+ x²⁴+ x²²+ x¹⁶+ x¹⁴+ x⁸+ x⁷+ x⁵+ x³+ x¹+ x⁰
        // has the reversed notation 0b11010101100000101000001010000001, so the value
        // that should be passed to MakeTable is 0xD5828281.
        crc32q := crc32.MakeTable(0xD5828281)
        fmt.Printf("%08x\n", crc32.Checksum([]byte("Hello world"), crc32q))
        

        Output:

        2964d064
        
        crc64 - Go Documentation Server
        ...

        Package crc64

        import "hash/crc64"
        Overview
        Index

        Overview ▾

        Package crc64 implements the 64-bit cyclic redundancy check, or CRC-64, checksum. See https://en.wikipedia.org/wiki/Cyclic_redundancy_check for information.

        Constants

        Predefined polynomials.

        const (
            // The ISO polynomial, defined in ISO 3309 and used in HDLC.
            ISO = 0xD800000000000000
        
            // The ECMA polynomial, defined in ECMA 182.
            ECMA = 0xC96C5795D7870F42
        )

        The size of a CRC-64 checksum in bytes.

        const Size = 8

        func Checksum

        func Checksum(data []byte, tab *Table) uint64

        Checksum returns the CRC-64 checksum of data using the polynomial represented by the Table.

        func New

        func New(tab *Table) hash.Hash64

        New creates a new hash.Hash64 computing the CRC-64 checksum using the polynomial represented by the Table. Its Sum method will lay the value out in big-endian byte order. The returned Hash64 also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

        func Update

        func Update(crc uint64, tab *Table, p []byte) uint64

        Update returns the result of adding the bytes in p to the crc.

        type Table

        Table is a 256-word table representing the polynomial for efficient processing.

        type Table [256]uint64

        func MakeTable

        func MakeTable(poly uint64) *Table

        MakeTable returns a Table constructed from the specified polynomial. The contents of this Table must not be modified.

        fnv - Go Documentation Server
        ...

        Package fnv

        import "hash/fnv"
        Overview
        Index

        Overview ▾

        Package fnv implements FNV-1 and FNV-1a, non-cryptographic hash functions created by Glenn Fowler, Landon Curt Noll, and Phong Vo. See https://en.wikipedia.org/wiki/Fowler-Noll-Vo_hash_function.

        All the hash.Hash implementations returned by this package also implement encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.

        func New128

        func New128() hash.Hash

        New128 returns a new 128-bit FNV-1 hash.Hash. Its Sum method will lay the value out in big-endian byte order.

        func New128a

        func New128a() hash.Hash

        New128a returns a new 128-bit FNV-1a hash.Hash. Its Sum method will lay the value out in big-endian byte order.

        func New32

        func New32() hash.Hash32

        New32 returns a new 32-bit FNV-1 hash.Hash. Its Sum method will lay the value out in big-endian byte order.

        func New32a

        func New32a() hash.Hash32

        New32a returns a new 32-bit FNV-1a hash.Hash. Its Sum method will lay the value out in big-endian byte order.

        func New64

        func New64() hash.Hash64

        New64 returns a new 64-bit FNV-1 hash.Hash. Its Sum method will lay the value out in big-endian byte order.

        func New64a

        func New64a() hash.Hash64

        New64a returns a new 64-bit FNV-1a hash.Hash. Its Sum method will lay the value out in big-endian byte order.

        maphash - Go Documentation Server
        ...

        Package maphash

        import "hash/maphash"
        Overview
        Index
        Examples

        Overview ▾

        Package maphash provides hash functions on byte sequences. These hash functions are intended to be used to implement hash tables or other data structures that need to map arbitrary strings or byte sequences to a uniform distribution on unsigned 64-bit integers. Each different instance of a hash table or data structure should use its own Seed.

        The hash functions are not cryptographically secure. (See crypto/sha256 and crypto/sha512 for cryptographic use.)

        Example

        Code:

        // The zero Hash value is valid and ready to use; setting an
        // initial seed is not necessary.
        var h maphash.Hash
        
        // Add a string to the hash, and print the current hash value.
        h.WriteString("hello, ")
        fmt.Printf("%#x\n", h.Sum64())
        
        // Append additional data (in the form of a byte array).
        h.Write([]byte{'w', 'o', 'r', 'l', 'd'})
        fmt.Printf("%#x\n", h.Sum64())
        
        // Reset discards all data previously added to the Hash, without
        // changing its seed.
        h.Reset()
        
        // Use SetSeed to create a new Hash h2 which will behave
        // identically to h.
        var h2 maphash.Hash
        h2.SetSeed(h.Seed())
        
        h.WriteString("same")
        h2.WriteString("same")
        fmt.Printf("%#x == %#x\n", h.Sum64(), h2.Sum64())
        

        func Bytes

        func Bytes(seed Seed, b []byte) uint64

        Bytes returns the hash of b with the given seed.

        Bytes is equivalent to, but more convenient and efficient than:

        var h Hash
        h.SetSeed(seed)
        h.Write(b)
        return h.Sum64()
        

        func String

        func String(seed Seed, s string) uint64

        String returns the hash of s with the given seed.

        String is equivalent to, but more convenient and efficient than:

        var h Hash
        h.SetSeed(seed)
        h.WriteString(s)
        return h.Sum64()
        

        type Hash

        A Hash computes a seeded hash of a byte sequence.

        The zero Hash is a valid Hash ready to use. A zero Hash chooses a random seed for itself during the first call to a Reset, Write, Seed, or Sum64 method. For control over the seed, use SetSeed.

        The computed hash values depend only on the initial seed and the sequence of bytes provided to the Hash object, not on the way in which the bytes are provided. For example, the three sequences

        h.Write([]byte{'f','o','o'})
        h.WriteByte('f'); h.WriteByte('o'); h.WriteByte('o')
        h.WriteString("foo")
        

        all have the same effect.

        Hashes are intended to be collision-resistant, even for situations where an adversary controls the byte sequences being hashed.

        A Hash is not safe for concurrent use by multiple goroutines, but a Seed is. If multiple goroutines must compute the same seeded hash, each can declare its own Hash and call SetSeed with a common Seed.

        type Hash struct {
            // contains filtered or unexported fields
        }
        

        func (*Hash) BlockSize

        func (h *Hash) BlockSize() int

        BlockSize returns h's block size.

        func (*Hash) Reset

        func (h *Hash) Reset()

        Reset discards all bytes added to h. (The seed remains the same.)

        func (*Hash) Seed

        func (h *Hash) Seed() Seed

        Seed returns h's seed value.

        func (*Hash) SetSeed

        func (h *Hash) SetSeed(seed Seed)

        SetSeed sets h to use seed, which must have been returned by MakeSeed or by another Hash.Seed method. Two Hash objects with the same seed behave identically. Two Hash objects with different seeds will very likely behave differently. Any bytes added to h before this call will be discarded.

        func (*Hash) Size

        func (h *Hash) Size() int

        Size returns h's hash value size, 8 bytes.

        func (*Hash) Sum

        func (h *Hash) Sum(b []byte) []byte

        Sum appends the hash's current 64-bit value to b. It exists for implementing hash.Hash. For direct calls, it is more efficient to use Hash.Sum64.

        func (*Hash) Sum64

        func (h *Hash) Sum64() uint64

        Sum64 returns h's current 64-bit value, which depends on h's seed and the sequence of bytes added to h since the last call to Hash.Reset or Hash.SetSeed.

        All bits of the Sum64 result are close to uniformly and independently distributed, so it can be safely reduced by using bit masking, shifting, or modular arithmetic.

        func (*Hash) Write

        func (h *Hash) Write(b []byte) (int, error)

        Write adds b to the sequence of bytes hashed by h. It always writes all of b and never fails; the count and error result are for implementing io.Writer.

        func (*Hash) WriteByte

        func (h *Hash) WriteByte(b byte) error

        WriteByte adds b to the sequence of bytes hashed by h. It never fails; the error result is for implementing io.ByteWriter.

        func (*Hash) WriteString

        func (h *Hash) WriteString(s string) (int, error)

        WriteString adds the bytes of s to the sequence of bytes hashed by h. It always writes all of s and never fails; the count and error result are for implementing io.StringWriter.

        type Seed

        A Seed is a random value that selects the specific hash function computed by a Hash. If two Hashes use the same Seeds, they will compute the same hash values for any given input. If two Hashes use different Seeds, they are very likely to compute distinct hash values for any given input.

        A Seed must be initialized by calling MakeSeed. The zero seed is uninitialized and not valid for use with Hash's SetSeed method.

        Each Seed value is local to a single process and cannot be serialized or otherwise recreated in a different process.

        type Seed struct {
            // contains filtered or unexported fields
        }
        

        func MakeSeed

        func MakeSeed() Seed

        MakeSeed returns a new random seed.

        html - Go Documentation Server
        ...

        Package html

        Overview ▾

        Package html provides functions for escaping and unescaping HTML text.

        func EscapeString

        func EscapeString(s string) string

        EscapeString escapes special characters like "<" to become "&lt;". It escapes only five such characters: <, >, &, ' and ". UnescapeString(EscapeString(s)) == s always holds, but the converse isn't always true.

        Example

        Code:

        const s = `"Fran & Freddie's Diner" <tasty@example.com>`
        fmt.Println(html.EscapeString(s))
        

        Output:

        &#34;Fran &amp; Freddie&#39;s Diner&#34; &lt;tasty@example.com&gt;
        

        func UnescapeString

        func UnescapeString(s string) string

        UnescapeString unescapes entities like "&lt;" to become "<". It unescapes a larger range of entities than EscapeString escapes. For example, "&aacute;" unescapes to "á", as does "&#225;" and "&#xE1;". UnescapeString(EscapeString(s)) == s always holds, but the converse isn't always true.

        Example

        Code:

        const s = `&quot;Fran &amp; Freddie&#39;s Diner&quot; &lt;tasty@example.com&gt;`
        fmt.Println(html.UnescapeString(s))
        

        Output:

        "Fran & Freddie's Diner" <tasty@example.com>
        

        Subdirectories

        Name Synopsis
        ..
        template Package template (html/template) implements data-driven templates for generating HTML output safe against code injection.
        template - Go Documentation Server
        ...

        Package template

        import "html/template"
        Overview
        Index
        Examples

        Overview ▾

        Package template (html/template) implements data-driven templates for generating HTML output safe against code injection. It provides the same interface as text/template and should be used instead of text/template whenever the output is HTML.

        The documentation here focuses on the security features of the package. For information about how to program the templates themselves, see the documentation for text/template.

        Introduction

        This package wraps text/template so you can share its template API to parse and execute HTML templates safely.

        tmpl, err := template.New("name").Parse(...)
        // Error checking elided
        err = tmpl.Execute(out, data)
        

        If successful, tmpl will now be injection-safe. Otherwise, err is an error defined in the docs for ErrorCode.

        HTML templates treat data values as plain text which should be encoded so they can be safely embedded in an HTML document. The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts.

        The security model used by this package assumes that template authors are trusted, while Execute's data parameter is not. More details are provided below.

        Example

        import "text/template"
        ...
        t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
        err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")
        

        produces

        Hello, <script>alert('you have been pwned')</script>!
        

        but the contextual autoescaping in html/template

        import "html/template"
        ...
        t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
        err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")
        

        produces safe, escaped HTML output

        Hello, &lt;script&gt;alert(&#39;you have been pwned&#39;)&lt;/script&gt;!
        

        Contexts

        This package understands HTML, CSS, JavaScript, and URIs. It adds sanitizing functions to each simple action pipeline, so given the excerpt

        <a href="/search?q={{.}}">{{.}}</a>
        

        At parse time each {{.}} is overwritten to add escaping functions as necessary. In this case it becomes

        <a href="/search?q={{. | urlescaper | attrescaper}}">{{. | htmlescaper}}</a>
        

        where urlescaper, attrescaper, and htmlescaper are aliases for internal escaping functions.

        For these internal escaping functions, if an action pipeline evaluates to a nil interface value, it is treated as though it were an empty string.

        Namespaced and data- attributes

        Attributes with a namespace are treated as if they had no namespace. Given the excerpt

        <a my:href="{{.}}"></a>
        

        At parse time the attribute will be treated as if it were just "href". So at parse time the template becomes:

        <a my:href="{{. | urlescaper | attrescaper}}"></a>
        

        Similarly to attributes with namespaces, attributes with a "data-" prefix are treated as if they had no "data-" prefix. So given

        <a data-href="{{.}}"></a>
        

        At parse time this becomes

        <a data-href="{{. | urlescaper | attrescaper}}"></a>
        

        If an attribute has both a namespace and a "data-" prefix, only the namespace will be removed when determining the context. For example

        <a my:data-href="{{.}}"></a>
        

        This is handled as if "my:data-href" was just "data-href" and not "href" as it would be if the "data-" prefix were to be ignored too. Thus at parse time this becomes just

        <a my:data-href="{{. | attrescaper}}"></a>
        

        As a special case, attributes with the namespace "xmlns" are always treated as containing URLs. Given the excerpts

        <a xmlns:title="{{.}}"></a>
        <a xmlns:href="{{.}}"></a>
        <a xmlns:onclick="{{.}}"></a>
        

        At parse time they become:

        <a xmlns:title="{{. | urlescaper | attrescaper}}"></a>
        <a xmlns:href="{{. | urlescaper | attrescaper}}"></a>
        <a xmlns:onclick="{{. | urlescaper | attrescaper}}"></a>
        

        Errors

        See the documentation of ErrorCode for details.

        A fuller picture

        The rest of this package comment may be skipped on first reading; it includes details necessary to understand escaping contexts and error messages. Most users will not need to understand these details.

        Contexts

        Assuming {{.}} is `O'Reilly: How are <i>you</i>?`, the table below shows how {{.}} appears when used in the context to the left.

        Context                          {{.}} After
        {{.}}                            O'Reilly: How are &lt;i&gt;you&lt;/i&gt;?
        <a title='{{.}}'>                O&#39;Reilly: How are you?
        <a href="/{{.}}">                O&#39;Reilly: How are %3ci%3eyou%3c/i%3e?
        <a href="?q={{.}}">              O&#39;Reilly%3a%20How%20are%3ci%3e...%3f
        <a onx='f("{{.}}")'>             O\x27Reilly: How are \x3ci\x3eyou...?
        <a onx='f({{.}})'>               "O\x27Reilly: How are \x3ci\x3eyou...?"
        <a onx='pattern = /{{.}}/;'>     O\x27Reilly: How are \x3ci\x3eyou...\x3f
        

        If used in an unsafe context, then the value might be filtered out:

        Context                          {{.}} After
        <a href="{{.}}">                 #ZgotmplZ
        

        since "O'Reilly:" is not an allowed protocol like "http:".

        If {{.}} is the innocuous word, `left`, then it can appear more widely,

        Context                              {{.}} After
        {{.}}                                left
        <a title='{{.}}'>                    left
        <a href='{{.}}'>                     left
        <a href='/{{.}}'>                    left
        <a href='?dir={{.}}'>                left
        <a style="border-{{.}}: 4px">        left
        <a style="align: {{.}}">             left
        <a style="background: '{{.}}'>       left
        <a style="background: url('{{.}}')>  left
        <style>p.{{.}} {color:red}</style>   left
        

        Non-string values can be used in JavaScript contexts. If {{.}} is

        struct{A,B string}{ "foo", "bar" }
        

        in the escaped template

        <script>var pair = {{.}};</script>
        

        then the template output is

        <script>var pair = {"A": "foo", "B": "bar"};</script>
        

        See package json to understand how non-string content is marshaled for embedding in JavaScript contexts.

        Typed Strings

        By default, this package assumes that all pipelines produce a plain text string. It adds escaping pipeline stages necessary to correctly and safely embed that plain text string in the appropriate context.

        When a data value is not plain text, you can make sure it is not over-escaped by marking it with its type.

        Types HTML, JS, URL, and others from content.go can carry safe content that is exempted from escaping.

        The template

        Hello, {{.}}!
        

        can be invoked with

        tmpl.Execute(out, template.HTML(`<b>World</b>`))
        

        to produce

        Hello, <b>World</b>!
        

        instead of the

        Hello, &lt;b&gt;World&lt;b&gt;!
        

        that would have been produced if {{.}} was a regular string.

        Security Model

        https://rawgit.com/mikesamuel/sanitized-jquery-templates/trunk/safetemplate.html#problem_definition defines "safe" as used by this package.

        This package assumes that template authors are trusted, that Execute's data parameter is not, and seeks to preserve the properties below in the face of untrusted data:

        Structure Preservation Property: "... when a template author writes an HTML tag in a safe templating language, the browser will interpret the corresponding portion of the output as a tag regardless of the values of untrusted data, and similarly for other structures such as attribute boundaries and JS and CSS string boundaries."

        Code Effect Property: "... only code specified by the template author should run as a result of injecting the template output into a page and all code specified by the template author should run as a result of the same."

        Least Surprise Property: "A developer (or code reviewer) familiar with HTML, CSS, and JavaScript, who knows that contextual autoescaping happens should be able to look at a {{.}} and correctly infer what sanitization happens."

        As a consequence of the Least Surprise Property, template actions within an ECMAScript 6 template literal are disabled by default. Handling string interpolation within these literals is rather complex resulting in no clear safe way to support it. To re-enable template actions within ECMAScript 6 template literals, use the GODEBUG=jstmpllitinterp=1 environment variable.

        Example

        Code:

        const tpl = `
        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="UTF-8">
                <title>{{.Title}}</title>
            </head>
            <body>
                {{range .Items}}<div>{{ . }}</div>{{else}}<div><strong>no rows</strong></div>{{end}}
            </body>
        </html>`
        
        check := func(err error) {
            if err != nil {
                log.Fatal(err)
            }
        }
        t, err := template.New("webpage").Parse(tpl)
        check(err)
        
        data := struct {
            Title string
            Items []string
        }{
            Title: "My page",
            Items: []string{
                "My photos",
                "My blog",
            },
        }
        
        err = t.Execute(os.Stdout, data)
        check(err)
        
        noItems := struct {
            Title string
            Items []string
        }{
            Title: "My another page",
            Items: []string{},
        }
        
        err = t.Execute(os.Stdout, noItems)
        check(err)
        
        

        Output:

        <!DOCTYPE html>
        <html>
        	<head>
        		<meta charset="UTF-8">
        		<title>My page</title>
        	</head>
        	<body>
        		<div>My photos</div><div>My blog</div>
        	</body>
        </html>
        <!DOCTYPE html>
        <html>
        	<head>
        		<meta charset="UTF-8">
        		<title>My another page</title>
        	</head>
        	<body>
        		<div><strong>no rows</strong></div>
        	</body>
        </html>
        

        Example (Autoescaping)

        Code:

        check := func(err error) {
            if err != nil {
                log.Fatal(err)
            }
        }
        t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
        check(err)
        err = t.ExecuteTemplate(os.Stdout, "T", "<script>alert('you have been pwned')</script>")
        check(err)
        

        Output:

        Hello, &lt;script&gt;alert(&#39;you have been pwned&#39;)&lt;/script&gt;!
        

        Example (Escape)

        Code:

        const s = `"Fran & Freddie's Diner" <tasty@example.com>`
        v := []any{`"Fran & Freddie's Diner"`, ' ', `<tasty@example.com>`}
        
        fmt.Println(template.HTMLEscapeString(s))
        template.HTMLEscape(os.Stdout, []byte(s))
        fmt.Fprintln(os.Stdout, "")
        fmt.Println(template.HTMLEscaper(v...))
        
        fmt.Println(template.JSEscapeString(s))
        template.JSEscape(os.Stdout, []byte(s))
        fmt.Fprintln(os.Stdout, "")
        fmt.Println(template.JSEscaper(v...))
        
        fmt.Println(template.URLQueryEscaper(v...))
        
        

        Output:

        &#34;Fran &amp; Freddie&#39;s Diner&#34; &lt;tasty@example.com&gt;
        &#34;Fran &amp; Freddie&#39;s Diner&#34; &lt;tasty@example.com&gt;
        &#34;Fran &amp; Freddie&#39;s Diner&#34;32&lt;tasty@example.com&gt;
        \"Fran \u0026 Freddie\'s Diner\" \u003Ctasty@example.com\u003E
        \"Fran \u0026 Freddie\'s Diner\" \u003Ctasty@example.com\u003E
        \"Fran \u0026 Freddie\'s Diner\"32\u003Ctasty@example.com\u003E
        %22Fran+%26+Freddie%27s+Diner%2232%3Ctasty%40example.com%3E
        

        Index ▾

        func HTMLEscape(w io.Writer, b []byte)
        func HTMLEscapeString(s string) string
        func HTMLEscaper(args ...any) string
        func IsTrue(val any) (truth, ok bool)
        func JSEscape(w io.Writer, b []byte)
        func JSEscapeString(s string) string
        func JSEscaper(args ...any) string
        func URLQueryEscaper(args ...any) string
        type CSS
        type Error
            func (e *Error) Error() string
        type ErrorCode
        type FuncMap
        type HTML
        type HTMLAttr
        type JS
        type JSStr
        type Srcset
        type Template
            func Must(t *Template, err error) *Template
            func New(name string) *Template
            func ParseFS(fs fs.FS, patterns ...string) (*Template, error)
            func ParseFiles(filenames ...string) (*Template, error)
            func ParseGlob(pattern string) (*Template, error)
            func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)
            func (t *Template) Clone() (*Template, error)
            func (t *Template) DefinedTemplates() string
            func (t *Template) Delims(left, right string) *Template
            func (t *Template) Execute(wr io.Writer, data any) error
            func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error
            func (t *Template) Funcs(funcMap FuncMap) *Template
            func (t *Template) Lookup(name string) *Template
            func (t *Template) Name() string
            func (t *Template) New(name string) *Template
            func (t *Template) Option(opt ...string) *Template
            func (t *Template) Parse(text string) (*Template, error)
            func (t *Template) ParseFS(fs fs.FS, patterns ...string) (*Template, error)
            func (t *Template) ParseFiles(filenames ...string) (*Template, error)
            func (t *Template) ParseGlob(pattern string) (*Template, error)
            func (t *Template) Templates() []*Template
        type URL

        Package files

        attr.go attr_string.go content.go context.go css.go delim_string.go doc.go element_string.go error.go escape.go html.go js.go jsctx_string.go state_string.go template.go transition.go url.go urlpart_string.go

        func HTMLEscape

        func HTMLEscape(w io.Writer, b []byte)

        HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.

        func HTMLEscapeString

        func HTMLEscapeString(s string) string

        HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.

        func HTMLEscaper

        func HTMLEscaper(args ...any) string

        HTMLEscaper returns the escaped HTML equivalent of the textual representation of its arguments.

        func IsTrue

        func IsTrue(val any) (truth, ok bool)

        IsTrue reports whether the value is 'true', in the sense of not the zero of its type, and whether the value has a meaningful truth value. This is the definition of truth used by if and other such actions.

        func JSEscape

        func JSEscape(w io.Writer, b []byte)

        JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.

        func JSEscapeString

        func JSEscapeString(s string) string

        JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.

        func JSEscaper

        func JSEscaper(args ...any) string

        JSEscaper returns the escaped JavaScript equivalent of the textual representation of its arguments.

        func URLQueryEscaper

        func URLQueryEscaper(args ...any) string

        URLQueryEscaper returns the escaped value of the textual representation of its arguments in a form suitable for embedding in a URL query.

        type CSS

        CSS encapsulates known safe content that matches any of:

        1. The CSS3 stylesheet production, such as `p { color: purple }`.
        2. The CSS3 rule production, such as `a[href=~"https:"].foo#bar`.
        3. CSS3 declaration productions, such as `color: red; margin: 2px`.
        4. The CSS3 value production, such as `rgba(0, 0, 255, 127)`.

        See https://www.w3.org/TR/css3-syntax/#parsing and https://web.archive.org/web/20090211114933/http://w3.org/TR/css3-syntax#style

        Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

        type CSS string

        type Error

        Error describes a problem encountered during template Escaping.

        type Error struct {
            // ErrorCode describes the kind of error.
            ErrorCode ErrorCode
            // Node is the node that caused the problem, if known.
            // If not nil, it overrides Name and Line.
            Node parse.Node
            // Name is the name of the template in which the error was encountered.
            Name string
            // Line is the line number of the error in the template source or 0.
            Line int
            // Description is a human-readable description of the problem.
            Description string
        }
        

        func (*Error) Error

        func (e *Error) Error() string

        type ErrorCode

        ErrorCode is a code for a kind of error.

        type ErrorCode int

        We define codes for each error that manifests while escaping templates, but escaped templates may also fail at runtime.

        Output: "ZgotmplZ" Example:

        <img src="{{.X}}">
        where {{.X}} evaluates to `javascript:...`
        

        Discussion:

        "ZgotmplZ" is a special value that indicates that unsafe content reached a
        CSS or URL context at runtime. The output of the example will be
          <img src="#ZgotmplZ">
        If the data comes from a trusted source, use content types to exempt it
        from filtering: URL(`javascript:...`).
        
        const (
            // OK indicates the lack of an error.
            OK ErrorCode = iota
        
            // ErrAmbigContext: "... appears in an ambiguous context within a URL"
            // Example:
            //   <a href="
            //      {{if .C}}
            //        /path/
            //      {{else}}
            //        /search?q=
            //      {{end}}
            //      {{.X}}
            //   ">
            // Discussion:
            //   {{.X}} is in an ambiguous URL context since, depending on {{.C}},
            //  it may be either a URL suffix or a query parameter.
            //   Moving {{.X}} into the condition removes the ambiguity:
            //   <a href="{{if .C}}/path/{{.X}}{{else}}/search?q={{.X}}">
            ErrAmbigContext
        
            // ErrBadHTML: "expected space, attr name, or end of tag, but got ...",
            //   "... in unquoted attr", "... in attribute name"
            // Example:
            //   <a href = /search?q=foo>
            //   <href=foo>
            //   <form na<e=...>
            //   <option selected<
            // Discussion:
            //   This is often due to a typo in an HTML element, but some runes
            //   are banned in tag names, attribute names, and unquoted attribute
            //   values because they can tickle parser ambiguities.
            //   Quoting all attributes is the best policy.
            ErrBadHTML
        
            // ErrBranchEnd: "{{if}} branches end in different contexts"
            // Example:
            //   {{if .C}}<a href="{{end}}{{.X}}
            // Discussion:
            //   Package html/template statically examines each path through an
            //   {{if}}, {{range}}, or {{with}} to escape any following pipelines.
            //   The example is ambiguous since {{.X}} might be an HTML text node,
            //   or a URL prefix in an HTML attribute. The context of {{.X}} is
            //   used to figure out how to escape it, but that context depends on
            //   the run-time value of {{.C}} which is not statically known.
            //
            //   The problem is usually something like missing quotes or angle
            //   brackets, or can be avoided by refactoring to put the two contexts
            //   into different branches of an if, range or with. If the problem
            //   is in a {{range}} over a collection that should never be empty,
            //   adding a dummy {{else}} can help.
            ErrBranchEnd
        
            // ErrEndContext: "... ends in a non-text context: ..."
            // Examples:
            //   <div
            //   <div title="no close quote>
            //   <script>f()
            // Discussion:
            //   Executed templates should produce a DocumentFragment of HTML.
            //   Templates that end without closing tags will trigger this error.
            //   Templates that should not be used in an HTML context or that
            //   produce incomplete Fragments should not be executed directly.
            //
            //   {{define "main"}} <script>{{template "helper"}}</script> {{end}}
            //   {{define "helper"}} document.write(' <div title=" ') {{end}}
            //
            //   "helper" does not produce a valid document fragment, so should
            //   not be Executed directly.
            ErrEndContext
        
            // ErrNoSuchTemplate: "no such template ..."
            // Examples:
            //   {{define "main"}}<div {{template "attrs"}}>{{end}}
            //   {{define "attrs"}}href="{{.URL}}"{{end}}
            // Discussion:
            //   Package html/template looks through template calls to compute the
            //   context.
            //   Here the {{.URL}} in "attrs" must be treated as a URL when called
            //   from "main", but you will get this error if "attrs" is not defined
            //   when "main" is parsed.
            ErrNoSuchTemplate
        
            // ErrOutputContext: "cannot compute output context for template ..."
            // Examples:
            //   {{define "t"}}{{if .T}}{{template "t" .T}}{{end}}{{.H}}",{{end}}
            // Discussion:
            //   A recursive template does not end in the same context in which it
            //   starts, and a reliable output context cannot be computed.
            //   Look for typos in the named template.
            //   If the template should not be called in the named start context,
            //   look for calls to that template in unexpected contexts.
            //   Maybe refactor recursive templates to not be recursive.
            ErrOutputContext
        
            // ErrPartialCharset: "unfinished JS regexp charset in ..."
            // Example:
            //     <script>var pattern = /foo[{{.Chars}}]/</script>
            // Discussion:
            //   Package html/template does not support interpolation into regular
            //   expression literal character sets.
            ErrPartialCharset
        
            // ErrPartialEscape: "unfinished escape sequence in ..."
            // Example:
            //   <script>alert("\{{.X}}")</script>
            // Discussion:
            //   Package html/template does not support actions following a
            //   backslash.
            //   This is usually an error and there are better solutions; for
            //   example
            //     <script>alert("{{.X}}")</script>
            //   should work, and if {{.X}} is a partial escape sequence such as
            //   "xA0", mark the whole sequence as safe content: JSStr(`\xA0`)
            ErrPartialEscape
        
            // ErrRangeLoopReentry: "on range loop re-entry: ..."
            // Example:
            //   <script>var x = [{{range .}}'{{.}},{{end}}]</script>
            // Discussion:
            //   If an iteration through a range would cause it to end in a
            //   different context than an earlier pass, there is no single context.
            //   In the example, there is missing a quote, so it is not clear
            //   whether {{.}} is meant to be inside a JS string or in a JS value
            //   context. The second iteration would produce something like
            //
            //     <script>var x = ['firstValue,'secondValue]</script>
            ErrRangeLoopReentry
        
            // ErrSlashAmbig: '/' could start a division or regexp.
            // Example:
            //   <script>
            //     {{if .C}}var x = 1{{end}}
            //     /-{{.N}}/i.test(x) ? doThis : doThat();
            //   </script>
            // Discussion:
            //   The example above could produce `var x = 1/-2/i.test(s)...`
            //   in which the first '/' is a mathematical division operator or it
            //   could produce `/-2/i.test(s)` in which the first '/' starts a
            //   regexp literal.
            //   Look for missing semicolons inside branches, and maybe add
            //   parentheses to make it clear which interpretation you intend.
            ErrSlashAmbig
        
            // ErrPredefinedEscaper: "predefined escaper ... disallowed in template"
            // Example:
            //   <div class={{. | html}}>Hello<div>
            // Discussion:
            //   Package html/template already contextually escapes all pipelines to
            //   produce HTML output safe against code injection. Manually escaping
            //   pipeline output using the predefined escapers "html" or "urlquery" is
            //   unnecessary, and may affect the correctness or safety of the escaped
            //   pipeline output in Go 1.8 and earlier.
            //
            //   In most cases, such as the given example, this error can be resolved by
            //   simply removing the predefined escaper from the pipeline and letting the
            //   contextual autoescaper handle the escaping of the pipeline. In other
            //   instances, where the predefined escaper occurs in the middle of a
            //   pipeline where subsequent commands expect escaped input, e.g.
            //     {{.X | html | makeALink}}
            //   where makeALink does
            //     return `<a href="`+input+`">link</a>`
            //   consider refactoring the surrounding template to make use of the
            //   contextual autoescaper, i.e.
            //     <a href="{{.X}}">link</a>
            //
            //   To ease migration to Go 1.9 and beyond, "html" and "urlquery" will
            //   continue to be allowed as the last command in a pipeline. However, if the
            //   pipeline occurs in an unquoted attribute value context, "html" is
            //   disallowed. Avoid using "html" and "urlquery" entirely in new templates.
            ErrPredefinedEscaper
        
            // ErrJSTemplate: "... appears in a JS template literal"
            // Example:
            //     <script>var tmpl = `{{.Interp}}`</script>
            // Discussion:
            //   Package html/template does not support actions inside of JS template
            //   literals.
            //
            // Deprecated: ErrJSTemplate is no longer returned when an action is present
            // in a JS template literal. Actions inside of JS template literals are now
            // escaped as expected.
            ErrJSTemplate
        )

        type FuncMap

        type FuncMap = template.FuncMap

        type HTML

        HTML encapsulates a known safe HTML document fragment. It should not be used for HTML from a third-party, or HTML with unclosed tags or comments. The outputs of a sound HTML sanitizer and a template escaped by this package are fine for use with HTML.

        Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

        type HTML string

        type HTMLAttr

        HTMLAttr encapsulates an HTML attribute from a trusted source, for example, ` dir="ltr"`.

        Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

        type HTMLAttr string

        type JS

        JS encapsulates a known safe EcmaScript5 Expression, for example, `(x + y * z())`. Template authors are responsible for ensuring that typed expressions do not break the intended precedence and that there is no statement/expression ambiguity as when passing an expression like "{ foo: bar() }\n['foo']()", which is both a valid Expression and a valid Program with a very different meaning.

        Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

        Using JS to include valid but untrusted JSON is not safe. A safe alternative is to parse the JSON with json.Unmarshal and then pass the resultant object into the template, where it will be converted to sanitized JSON when presented in a JavaScript context.

        type JS string

        type JSStr

        JSStr encapsulates a sequence of characters meant to be embedded between quotes in a JavaScript expression. The string must match a series of StringCharacters:

        StringCharacter :: SourceCharacter but not `\` or LineTerminator
                         | EscapeSequence
        

        Note that LineContinuations are not allowed. JSStr("foo\\nbar") is fine, but JSStr("foo\\\nbar") is not.

        Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

        type JSStr string

        type Srcset

        Srcset encapsulates a known safe srcset attribute (see https://w3c.github.io/html/semantics-embedded-content.html#element-attrdef-img-srcset).

        Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

        type Srcset string

        type Template

        Template is a specialized Template from "text/template" that produces a safe HTML document fragment.

        type Template struct {
        
            // The underlying template's parse tree, updated to be HTML-safe.
            Tree *parse.Tree
            // contains filtered or unexported fields
        }
        

        Example (Block)

        Code:

        const (
            master  = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}`
            overlay = `{{define "list"}} {{join . ", "}}{{end}} `
        )
        var (
            funcs     = template.FuncMap{"join": strings.Join}
            guardians = []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"}
        )
        masterTmpl, err := template.New("master").Funcs(funcs).Parse(master)
        if err != nil {
            log.Fatal(err)
        }
        overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay)
        if err != nil {
            log.Fatal(err)
        }
        if err := masterTmpl.Execute(os.Stdout, guardians); err != nil {
            log.Fatal(err)
        }
        if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil {
            log.Fatal(err)
        }
        

        Output:

        Names:
        - Gamora
        - Groot
        - Nebula
        - Rocket
        - Star-Lord
        Names: Gamora, Groot, Nebula, Rocket, Star-Lord
        

        Example (Glob)

        Here we demonstrate loading a set of templates from a directory.

        Code:

        // Here we create a temporary directory and populate it with our sample
        // template definition files; usually the template files would already
        // exist in some location known to the program.
        dir := createTestDir([]templateFile{
            // T0.tmpl is a plain template file that just invokes T1.
            {"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`},
            // T1.tmpl defines a template, T1 that invokes T2.
            {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
            // T2.tmpl defines a template T2.
            {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
        })
        // Clean up after the test; another quirk of running as an example.
        defer os.RemoveAll(dir)
        
        // pattern is the glob pattern used to find all the template files.
        pattern := filepath.Join(dir, "*.tmpl")
        
        // Here starts the example proper.
        // T0.tmpl is the first name matched, so it becomes the starting template,
        // the value returned by ParseGlob.
        tmpl := template.Must(template.ParseGlob(pattern))
        
        err := tmpl.Execute(os.Stdout, nil)
        if err != nil {
            log.Fatalf("template execution: %s", err)
        }
        

        Output:

        T0 invokes T1: (T1 invokes T2: (This is T2))
        

        Example (Helpers)

        This example demonstrates one way to share some templates and use them in different contexts. In this variant we add multiple driver templates by hand to an existing bundle of templates.

        Code:

        // Here we create a temporary directory and populate it with our sample
        // template definition files; usually the template files would already
        // exist in some location known to the program.
        dir := createTestDir([]templateFile{
            // T1.tmpl defines a template, T1 that invokes T2.
            {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
            // T2.tmpl defines a template T2.
            {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
        })
        // Clean up after the test; another quirk of running as an example.
        defer os.RemoveAll(dir)
        
        // pattern is the glob pattern used to find all the template files.
        pattern := filepath.Join(dir, "*.tmpl")
        
        // Here starts the example proper.
        // Load the helpers.
        templates := template.Must(template.ParseGlob(pattern))
        // Add one driver template to the bunch; we do this with an explicit template definition.
        _, err := templates.Parse("{{define `driver1`}}Driver 1 calls T1: ({{template `T1`}})\n{{end}}")
        if err != nil {
            log.Fatal("parsing driver1: ", err)
        }
        // Add another driver template.
        _, err = templates.Parse("{{define `driver2`}}Driver 2 calls T2: ({{template `T2`}})\n{{end}}")
        if err != nil {
            log.Fatal("parsing driver2: ", err)
        }
        // We load all the templates before execution. This package does not require
        // that behavior but html/template's escaping does, so it's a good habit.
        err = templates.ExecuteTemplate(os.Stdout, "driver1", nil)
        if err != nil {
            log.Fatalf("driver1 execution: %s", err)
        }
        err = templates.ExecuteTemplate(os.Stdout, "driver2", nil)
        if err != nil {
            log.Fatalf("driver2 execution: %s", err)
        }
        

        Output:

        Driver 1 calls T1: (T1 invokes T2: (This is T2))
        Driver 2 calls T2: (This is T2)
        

        Example (Parsefiles)

        Here we demonstrate loading a set of templates from files in different directories

        Code:

        // Here we create different temporary directories and populate them with our sample
        // template definition files; usually the template files would already
        // exist in some location known to the program.
        dir1 := createTestDir([]templateFile{
            // T1.tmpl is a plain template file that just invokes T2.
            {"T1.tmpl", `T1 invokes T2: ({{template "T2"}})`},
        })
        
        dir2 := createTestDir([]templateFile{
            // T2.tmpl defines a template T2.
            {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
        })
        
        // Clean up after the test; another quirk of running as an example.
        defer func(dirs ...string) {
            for _, dir := range dirs {
                os.RemoveAll(dir)
            }
        }(dir1, dir2)
        
        // Here starts the example proper.
        // Let's just parse only dir1/T0 and dir2/T2
        paths := []string{
            filepath.Join(dir1, "T1.tmpl"),
            filepath.Join(dir2, "T2.tmpl"),
        }
        tmpl := template.Must(template.ParseFiles(paths...))
        
        err := tmpl.Execute(os.Stdout, nil)
        if err != nil {
            log.Fatalf("template execution: %s", err)
        }
        

        Output:

        T1 invokes T2: (This is T2)
        

        Example (Share)

        This example demonstrates how to use one group of driver templates with distinct sets of helper templates.

        Code:

        // Here we create a temporary directory and populate it with our sample
        // template definition files; usually the template files would already
        // exist in some location known to the program.
        dir := createTestDir([]templateFile{
            // T0.tmpl is a plain template file that just invokes T1.
            {"T0.tmpl", "T0 ({{.}} version) invokes T1: ({{template `T1`}})\n"},
            // T1.tmpl defines a template, T1 that invokes T2. Note T2 is not defined
            {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
        })
        // Clean up after the test; another quirk of running as an example.
        defer os.RemoveAll(dir)
        
        // pattern is the glob pattern used to find all the template files.
        pattern := filepath.Join(dir, "*.tmpl")
        
        // Here starts the example proper.
        // Load the drivers.
        drivers := template.Must(template.ParseGlob(pattern))
        
        // We must define an implementation of the T2 template. First we clone
        // the drivers, then add a definition of T2 to the template name space.
        
        // 1. Clone the helper set to create a new name space from which to run them.
        first, err := drivers.Clone()
        if err != nil {
            log.Fatal("cloning helpers: ", err)
        }
        // 2. Define T2, version A, and parse it.
        _, err = first.Parse("{{define `T2`}}T2, version A{{end}}")
        if err != nil {
            log.Fatal("parsing T2: ", err)
        }
        
        // Now repeat the whole thing, using a different version of T2.
        // 1. Clone the drivers.
        second, err := drivers.Clone()
        if err != nil {
            log.Fatal("cloning drivers: ", err)
        }
        // 2. Define T2, version B, and parse it.
        _, err = second.Parse("{{define `T2`}}T2, version B{{end}}")
        if err != nil {
            log.Fatal("parsing T2: ", err)
        }
        
        // Execute the templates in the reverse order to verify the
        // first is unaffected by the second.
        err = second.ExecuteTemplate(os.Stdout, "T0.tmpl", "second")
        if err != nil {
            log.Fatalf("second execution: %s", err)
        }
        err = first.ExecuteTemplate(os.Stdout, "T0.tmpl", "first")
        if err != nil {
            log.Fatalf("first: execution: %s", err)
        }
        
        

        Output:

        T0 (second version) invokes T1: (T1 invokes T2: (T2, version B))
        T0 (first version) invokes T1: (T1 invokes T2: (T2, version A))
        

        func Must

        func Must(t *Template, err error) *Template

        Must is a helper that wraps a call to a function returning (*Template, error) and panics if the error is non-nil. It is intended for use in variable initializations such as

        var t = template.Must(template.New("name").Parse("html"))
        

        func New

        func New(name string) *Template

        New allocates a new HTML template with the given name.

        func ParseFS

        func ParseFS(fs fs.FS, patterns ...string) (*Template, error)

        ParseFS is like ParseFiles or ParseGlob but reads from the file system fs instead of the host operating system's file system. It accepts a list of glob patterns. (Note that most file names serve as glob patterns matching only themselves.)

        func ParseFiles

        func ParseFiles(filenames ...string) (*Template, error)

        ParseFiles creates a new Template and parses the template definitions from the named files. The returned template's name will have the (base) name and (parsed) contents of the first file. There must be at least one file. If an error occurs, parsing stops and the returned *Template is nil.

        When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results. For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template named "foo", while "a/foo" is unavailable.

        func ParseGlob

        func ParseGlob(pattern string) (*Template, error)

        ParseGlob creates a new Template and parses the template definitions from the files identified by the pattern. The files are matched according to the semantics of filepath.Match, and the pattern must match at least one file. The returned template will have the (base) name and (parsed) contents of the first file matched by the pattern. ParseGlob is equivalent to calling ParseFiles with the list of files matched by the pattern.

        When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

        func (*Template) AddParseTree

        func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)

        AddParseTree creates a new template with the name and parse tree and associates it with t.

        It returns an error if t or any associated template has already been executed.

        func (*Template) Clone

        func (t *Template) Clone() (*Template, error)

        Clone returns a duplicate of the template, including all associated templates. The actual representation is not copied, but the name space of associated templates is, so further calls to Parse in the copy will add templates to the copy but not to the original. Clone can be used to prepare common templates and use them with variant definitions for other templates by adding the variants after the clone is made.

        It returns an error if t has already been executed.

        func (*Template) DefinedTemplates

        func (t *Template) DefinedTemplates() string

        DefinedTemplates returns a string listing the defined templates, prefixed by the string "; defined templates are: ". If there are none, it returns the empty string. Used to generate an error message.

        func (*Template) Delims

        func (t *Template) Delims(left, right string) *Template

        Delims sets the action delimiters to the specified strings, to be used in subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template definitions will inherit the settings. An empty delimiter stands for the corresponding default: {{ or }}. The return value is the template, so calls can be chained.

        Example

        Code:

        const text = "<<.Greeting>> {{.Name}}"
        
        data := struct {
            Greeting string
            Name     string
        }{
            Greeting: "Hello",
            Name:     "Joe",
        }
        
        t := template.Must(template.New("tpl").Delims("<<", ">>").Parse(text))
        
        err := t.Execute(os.Stdout, data)
        if err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        Hello {{.Name}}
        

        func (*Template) Execute

        func (t *Template) Execute(wr io.Writer, data any) error

        Execute applies a parsed template to the specified data object, writing the output to wr. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

        func (*Template) ExecuteTemplate

        func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error

        ExecuteTemplate applies the template associated with t that has the given name to the specified data object and writes the output to wr. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

        func (*Template) Funcs

        func (t *Template) Funcs(funcMap FuncMap) *Template

        Funcs adds the elements of the argument map to the template's function map. It must be called before the template is parsed. It panics if a value in the map is not a function with appropriate return type. However, it is legal to overwrite elements of the map. The return value is the template, so calls can be chained.

        func (*Template) Lookup

        func (t *Template) Lookup(name string) *Template

        Lookup returns the template with the given name that is associated with t, or nil if there is no such template.

        func (*Template) Name

        func (t *Template) Name() string

        Name returns the name of the template.

        func (*Template) New

        func (t *Template) New(name string) *Template

        New allocates a new HTML template associated with the given one and with the same delimiters. The association, which is transitive, allows one template to invoke another with a {{template}} action.

        If a template with the given name already exists, the new HTML template will replace it. The existing template will be reset and disassociated with t.

        func (*Template) Option

        func (t *Template) Option(opt ...string) *Template

        Option sets options for the template. Options are described by strings, either a simple string or "key=value". There can be at most one equals sign in an option string. If the option string is unrecognized or otherwise invalid, Option panics.

        Known options:

        missingkey: Control the behavior during execution if a map is indexed with a key that is not present in the map.

        "missingkey=default" or "missingkey=invalid"
        	The default behavior: Do nothing and continue execution.
        	If printed, the result of the index operation is the string
        	"<no value>".
        "missingkey=zero"
        	The operation returns the zero value for the map type's element.
        "missingkey=error"
        	Execution stops immediately with an error.
        

        func (*Template) Parse

        func (t *Template) Parse(text string) (*Template, error)

        Parse parses text as a template body for t. Named template definitions ({{define ...}} or {{block ...}} statements) in text define additional templates associated with t and are removed from the definition of t itself.

        Templates can be redefined in successive calls to Parse, before the first use of Execute on t or any associated template. A template definition with a body containing only white space and comments is considered empty and will not replace an existing template's body. This allows using Parse to add new named template definitions without overwriting the main template body.

        func (*Template) ParseFS

        func (t *Template) ParseFS(fs fs.FS, patterns ...string) (*Template, error)

        ParseFS is like ParseFiles or ParseGlob but reads from the file system fs instead of the host operating system's file system. It accepts a list of glob patterns. (Note that most file names serve as glob patterns matching only themselves.)

        func (*Template) ParseFiles

        func (t *Template) ParseFiles(filenames ...string) (*Template, error)

        ParseFiles parses the named files and associates the resulting templates with t. If an error occurs, parsing stops and the returned template is nil; otherwise it is t. There must be at least one file.

        When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

        ParseFiles returns an error if t or any associated template has already been executed.

        func (*Template) ParseGlob

        func (t *Template) ParseGlob(pattern string) (*Template, error)

        ParseGlob parses the template definitions in the files identified by the pattern and associates the resulting templates with t. The files are matched according to the semantics of filepath.Match, and the pattern must match at least one file. ParseGlob is equivalent to calling t.ParseFiles with the list of files matched by the pattern.

        When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

        ParseGlob returns an error if t or any associated template has already been executed.

        func (*Template) Templates

        func (t *Template) Templates() []*Template

        Templates returns a slice of the templates associated with t, including t itself.

        type URL

        URL encapsulates a known safe URL or URL substring (see RFC 3986). A URL like `javascript:checkThatFormNotEditedBeforeLeavingPage()` from a trusted source should go in the page, but by default dynamic `javascript:` URLs are filtered out since they are a frequently exploited injection vector.

        Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

        type URL string
        image - Go Documentation Server
        ...

        Package image

        Overview ▾

        Package image implements a basic 2-D image library.

        The fundamental interface is called Image. An Image contains colors, which are described in the image/color package.

        Values of the Image interface are created either by calling functions such as NewRGBA and NewPaletted, or by calling Decode on an io.Reader containing image data in a format such as GIF, JPEG or PNG. Decoding any particular image format requires the prior registration of a decoder function. Registration is typically automatic as a side effect of initializing that format's package so that, to decode a PNG image, it suffices to have

        import _ "image/png"
        

        in a program's main package. The _ means to import a package purely for its initialization side effects.

        See "The Go image package" for more details: https://golang.org/doc/articles/image_package.html

        Security Considerations

        The image package can be used to parse arbitrarily large images, which can cause resource exhaustion on machines which do not have enough memory to store them. When operating on arbitrary images, DecodeConfig should be called before Decode, so that the program can decide whether the image, as defined in the returned header, can be safely decoded with the available resources. A call to Decode which produces an extremely large image, as defined in the header returned by DecodeConfig, is not considered a security issue, regardless of whether the image is itself malformed or not. A call to DecodeConfig which returns a header which does not match the image returned by Decode may be considered a security issue, and should be reported per the [Go Security Policy](https://go.dev/security/policy).

        Example

        Code:

        // Decode the JPEG data. If reading from file, create a reader with
        //
        // reader, err := os.Open("testdata/video-001.q50.420.jpeg")
        // if err != nil {
        //     log.Fatal(err)
        // }
        // defer reader.Close()
        reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))
        m, _, err := image.Decode(reader)
        if err != nil {
            log.Fatal(err)
        }
        bounds := m.Bounds()
        
        // Calculate a 16-bin histogram for m's red, green, blue and alpha components.
        //
        // An image's bounds do not necessarily start at (0, 0), so the two loops start
        // at bounds.Min.Y and bounds.Min.X. Looping over Y first and X second is more
        // likely to result in better memory access patterns than X first and Y second.
        var histogram [16][4]int
        for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
            for x := bounds.Min.X; x < bounds.Max.X; x++ {
                r, g, b, a := m.At(x, y).RGBA()
                // A color's RGBA method returns values in the range [0, 65535].
                // Shifting by 12 reduces this to the range [0, 15].
                histogram[r>>12][0]++
                histogram[g>>12][1]++
                histogram[b>>12][2]++
                histogram[a>>12][3]++
            }
        }
        
        // Print the results.
        fmt.Printf("%-14s %6s %6s %6s %6s\n", "bin", "red", "green", "blue", "alpha")
        for i, x := range histogram {
            fmt.Printf("0x%04x-0x%04x: %6d %6d %6d %6d\n", i<<12, (i+1)<<12-1, x[0], x[1], x[2], x[3])
        }
        

        Output:

        bin               red  green   blue  alpha
        0x0000-0x0fff:    364    790   7242      0
        0x1000-0x1fff:    645   2967   1039      0
        0x2000-0x2fff:   1072   2299    979      0
        0x3000-0x3fff:    820   2266    980      0
        0x4000-0x4fff:    537   1305    541      0
        0x5000-0x5fff:    319    962    261      0
        0x6000-0x6fff:    322    375    177      0
        0x7000-0x7fff:    601    279    214      0
        0x8000-0x8fff:   3478    227    273      0
        0x9000-0x9fff:   2260    234    329      0
        0xa000-0xafff:    921    282    373      0
        0xb000-0xbfff:    321    335    397      0
        0xc000-0xcfff:    229    388    298      0
        0xd000-0xdfff:    260    414    277      0
        0xe000-0xefff:    516    428    298      0
        0xf000-0xffff:   2785   1899   1772  15450
        

        Example (DecodeConfig)

        Code:

        reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))
        config, format, err := image.DecodeConfig(reader)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("Width:", config.Width, "Height:", config.Height, "Format:", format)
        

        Index ▾

        Variables
        func RegisterFormat(name, magic string, decode func(io.Reader) (Image, error), decodeConfig func(io.Reader) (Config, error))
        type Alpha
            func NewAlpha(r Rectangle) *Alpha
            func (p *Alpha) AlphaAt(x, y int) color.Alpha
            func (p *Alpha) At(x, y int) color.Color
            func (p *Alpha) Bounds() Rectangle
            func (p *Alpha) ColorModel() color.Model
            func (p *Alpha) Opaque() bool
            func (p *Alpha) PixOffset(x, y int) int
            func (p *Alpha) RGBA64At(x, y int) color.RGBA64
            func (p *Alpha) Set(x, y int, c color.Color)
            func (p *Alpha) SetAlpha(x, y int, c color.Alpha)
            func (p *Alpha) SetRGBA64(x, y int, c color.RGBA64)
            func (p *Alpha) SubImage(r Rectangle) Image
        type Alpha16
            func NewAlpha16(r Rectangle) *Alpha16
            func (p *Alpha16) Alpha16At(x, y int) color.Alpha16
            func (p *Alpha16) At(x, y int) color.Color
            func (p *Alpha16) Bounds() Rectangle
            func (p *Alpha16) ColorModel() color.Model
            func (p *Alpha16) Opaque() bool
            func (p *Alpha16) PixOffset(x, y int) int
            func (p *Alpha16) RGBA64At(x, y int) color.RGBA64
            func (p *Alpha16) Set(x, y int, c color.Color)
            func (p *Alpha16) SetAlpha16(x, y int, c color.Alpha16)
            func (p *Alpha16) SetRGBA64(x, y int, c color.RGBA64)
            func (p *Alpha16) SubImage(r Rectangle) Image
        type CMYK
            func NewCMYK(r Rectangle) *CMYK
            func (p *CMYK) At(x, y int) color.Color
            func (p *CMYK) Bounds() Rectangle
            func (p *CMYK) CMYKAt(x, y int) color.CMYK
            func (p *CMYK) ColorModel() color.Model
            func (p *CMYK) Opaque() bool
            func (p *CMYK) PixOffset(x, y int) int
            func (p *CMYK) RGBA64At(x, y int) color.RGBA64
            func (p *CMYK) Set(x, y int, c color.Color)
            func (p *CMYK) SetCMYK(x, y int, c color.CMYK)
            func (p *CMYK) SetRGBA64(x, y int, c color.RGBA64)
            func (p *CMYK) SubImage(r Rectangle) Image
        type Config
            func DecodeConfig(r io.Reader) (Config, string, error)
        type Gray
            func NewGray(r Rectangle) *Gray
            func (p *Gray) At(x, y int) color.Color
            func (p *Gray) Bounds() Rectangle
            func (p *Gray) ColorModel() color.Model
            func (p *Gray) GrayAt(x, y int) color.Gray
            func (p *Gray) Opaque() bool
            func (p *Gray) PixOffset(x, y int) int
            func (p *Gray) RGBA64At(x, y int) color.RGBA64
            func (p *Gray) Set(x, y int, c color.Color)
            func (p *Gray) SetGray(x, y int, c color.Gray)
            func (p *Gray) SetRGBA64(x, y int, c color.RGBA64)
            func (p *Gray) SubImage(r Rectangle) Image
        type Gray16
            func NewGray16(r Rectangle) *Gray16
            func (p *Gray16) At(x, y int) color.Color
            func (p *Gray16) Bounds() Rectangle
            func (p *Gray16) ColorModel() color.Model
            func (p *Gray16) Gray16At(x, y int) color.Gray16
            func (p *Gray16) Opaque() bool
            func (p *Gray16) PixOffset(x, y int) int
            func (p *Gray16) RGBA64At(x, y int) color.RGBA64
            func (p *Gray16) Set(x, y int, c color.Color)
            func (p *Gray16) SetGray16(x, y int, c color.Gray16)
            func (p *Gray16) SetRGBA64(x, y int, c color.RGBA64)
            func (p *Gray16) SubImage(r Rectangle) Image
        type Image
            func Decode(r io.Reader) (Image, string, error)
        type NRGBA
            func NewNRGBA(r Rectangle) *NRGBA
            func (p *NRGBA) At(x, y int) color.Color
            func (p *NRGBA) Bounds() Rectangle
            func (p *NRGBA) ColorModel() color.Model
            func (p *NRGBA) NRGBAAt(x, y int) color.NRGBA
            func (p *NRGBA) Opaque() bool
            func (p *NRGBA) PixOffset(x, y int) int
            func (p *NRGBA) RGBA64At(x, y int) color.RGBA64
            func (p *NRGBA) Set(x, y int, c color.Color)
            func (p *NRGBA) SetNRGBA(x, y int, c color.NRGBA)
            func (p *NRGBA) SetRGBA64(x, y int, c color.RGBA64)
            func (p *NRGBA) SubImage(r Rectangle) Image
        type NRGBA64
            func NewNRGBA64(r Rectangle) *NRGBA64
            func (p *NRGBA64) At(x, y int) color.Color
            func (p *NRGBA64) Bounds() Rectangle
            func (p *NRGBA64) ColorModel() color.Model
            func (p *NRGBA64) NRGBA64At(x, y int) color.NRGBA64
            func (p *NRGBA64) Opaque() bool
            func (p *NRGBA64) PixOffset(x, y int) int
            func (p *NRGBA64) RGBA64At(x, y int) color.RGBA64
            func (p *NRGBA64) Set(x, y int, c color.Color)
            func (p *NRGBA64) SetNRGBA64(x, y int, c color.NRGBA64)
            func (p *NRGBA64) SetRGBA64(x, y int, c color.RGBA64)
            func (p *NRGBA64) SubImage(r Rectangle) Image
        type NYCbCrA
            func NewNYCbCrA(r Rectangle, subsampleRatio YCbCrSubsampleRatio) *NYCbCrA
            func (p *NYCbCrA) AOffset(x, y int) int
            func (p *NYCbCrA) At(x, y int) color.Color
            func (p *NYCbCrA) ColorModel() color.Model
            func (p *NYCbCrA) NYCbCrAAt(x, y int) color.NYCbCrA
            func (p *NYCbCrA) Opaque() bool
            func (p *NYCbCrA) RGBA64At(x, y int) color.RGBA64
            func (p *NYCbCrA) SubImage(r Rectangle) Image
        type Paletted
            func NewPaletted(r Rectangle, p color.Palette) *Paletted
            func (p *Paletted) At(x, y int) color.Color
            func (p *Paletted) Bounds() Rectangle
            func (p *Paletted) ColorIndexAt(x, y int) uint8
            func (p *Paletted) ColorModel() color.Model
            func (p *Paletted) Opaque() bool
            func (p *Paletted) PixOffset(x, y int) int
            func (p *Paletted) RGBA64At(x, y int) color.RGBA64
            func (p *Paletted) Set(x, y int, c color.Color)
            func (p *Paletted) SetColorIndex(x, y int, index uint8)
            func (p *Paletted) SetRGBA64(x, y int, c color.RGBA64)
            func (p *Paletted) SubImage(r Rectangle) Image
        type PalettedImage
        type Point
            func Pt(X, Y int) Point
            func (p Point) Add(q Point) Point
            func (p Point) Div(k int) Point
            func (p Point) Eq(q Point) bool
            func (p Point) In(r Rectangle) bool
            func (p Point) Mod(r Rectangle) Point
            func (p Point) Mul(k int) Point
            func (p Point) String() string
            func (p Point) Sub(q Point) Point
        type RGBA
            func NewRGBA(r Rectangle) *RGBA
            func (p *RGBA) At(x, y int) color.Color
            func (p *RGBA) Bounds() Rectangle
            func (p *RGBA) ColorModel() color.Model
            func (p *RGBA) Opaque() bool
            func (p *RGBA) PixOffset(x, y int) int
            func (p *RGBA) RGBA64At(x, y int) color.RGBA64
            func (p *RGBA) RGBAAt(x, y int) color.RGBA
            func (p *RGBA) Set(x, y int, c color.Color)
            func (p *RGBA) SetRGBA(x, y int, c color.RGBA)
            func (p *RGBA) SetRGBA64(x, y int, c color.RGBA64)
            func (p *RGBA) SubImage(r Rectangle) Image
        type RGBA64
            func NewRGBA64(r Rectangle) *RGBA64
            func (p *RGBA64) At(x, y int) color.Color
            func (p *RGBA64) Bounds() Rectangle
            func (p *RGBA64) ColorModel() color.Model
            func (p *RGBA64) Opaque() bool
            func (p *RGBA64) PixOffset(x, y int) int
            func (p *RGBA64) RGBA64At(x, y int) color.RGBA64
            func (p *RGBA64) Set(x, y int, c color.Color)
            func (p *RGBA64) SetRGBA64(x, y int, c color.RGBA64)
            func (p *RGBA64) SubImage(r Rectangle) Image
        type RGBA64Image
        type Rectangle
            func Rect(x0, y0, x1, y1 int) Rectangle
            func (r Rectangle) Add(p Point) Rectangle
            func (r Rectangle) At(x, y int) color.Color
            func (r Rectangle) Bounds() Rectangle
            func (r Rectangle) Canon() Rectangle
            func (r Rectangle) ColorModel() color.Model
            func (r Rectangle) Dx() int
            func (r Rectangle) Dy() int
            func (r Rectangle) Empty() bool
            func (r Rectangle) Eq(s Rectangle) bool
            func (r Rectangle) In(s Rectangle) bool
            func (r Rectangle) Inset(n int) Rectangle
            func (r Rectangle) Intersect(s Rectangle) Rectangle
            func (r Rectangle) Overlaps(s Rectangle) bool
            func (r Rectangle) RGBA64At(x, y int) color.RGBA64
            func (r Rectangle) Size() Point
            func (r Rectangle) String() string
            func (r Rectangle) Sub(p Point) Rectangle
            func (r Rectangle) Union(s Rectangle) Rectangle
        type Uniform
            func NewUniform(c color.Color) *Uniform
            func (c *Uniform) At(x, y int) color.Color
            func (c *Uniform) Bounds() Rectangle
            func (c *Uniform) ColorModel() color.Model
            func (c *Uniform) Convert(color.Color) color.Color
            func (c *Uniform) Opaque() bool
            func (c *Uniform) RGBA() (r, g, b, a uint32)
            func (c *Uniform) RGBA64At(x, y int) color.RGBA64
        type YCbCr
            func NewYCbCr(r Rectangle, subsampleRatio YCbCrSubsampleRatio) *YCbCr
            func (p *YCbCr) At(x, y int) color.Color
            func (p *YCbCr) Bounds() Rectangle
            func (p *YCbCr) COffset(x, y int) int
            func (p *YCbCr) ColorModel() color.Model
            func (p *YCbCr) Opaque() bool
            func (p *YCbCr) RGBA64At(x, y int) color.RGBA64
            func (p *YCbCr) SubImage(r Rectangle) Image
            func (p *YCbCr) YCbCrAt(x, y int) color.YCbCr
            func (p *YCbCr) YOffset(x, y int) int
        type YCbCrSubsampleRatio
            func (s YCbCrSubsampleRatio) String() string

        Examples

        Package
        Package (DecodeConfig)

        Package files

        format.go geom.go image.go names.go ycbcr.go

        Variables

        var (
            // Black is an opaque black uniform image.
            Black = NewUniform(color.Black)
            // White is an opaque white uniform image.
            White = NewUniform(color.White)
            // Transparent is a fully transparent uniform image.
            Transparent = NewUniform(color.Transparent)
            // Opaque is a fully opaque uniform image.
            Opaque = NewUniform(color.Opaque)
        )

        ErrFormat indicates that decoding encountered an unknown format.

        var ErrFormat = errors.New("image: unknown format")

        func RegisterFormat

        func RegisterFormat(name, magic string, decode func(io.Reader) (Image, error), decodeConfig func(io.Reader) (Config, error))

        RegisterFormat registers an image format for use by Decode. Name is the name of the format, like "jpeg" or "png". Magic is the magic prefix that identifies the format's encoding. The magic string can contain "?" wildcards that each match any one byte. Decode is the function that decodes the encoded image. DecodeConfig is the function that decodes just its configuration.

        type Alpha

        Alpha is an in-memory image whose At method returns color.Alpha values.

        type Alpha struct {
            // Pix holds the image's pixels, as alpha values. The pixel at
            // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
            Pix []uint8
            // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
            Stride int
            // Rect is the image's bounds.
            Rect Rectangle
        }
        

        func NewAlpha

        func NewAlpha(r Rectangle) *Alpha

        NewAlpha returns a new Alpha image with the given bounds.

        func (*Alpha) AlphaAt

        func (p *Alpha) AlphaAt(x, y int) color.Alpha

        func (*Alpha) At

        func (p *Alpha) At(x, y int) color.Color

        func (*Alpha) Bounds

        func (p *Alpha) Bounds() Rectangle

        func (*Alpha) ColorModel

        func (p *Alpha) ColorModel() color.Model

        func (*Alpha) Opaque

        func (p *Alpha) Opaque() bool

        Opaque scans the entire image and reports whether it is fully opaque.

        func (*Alpha) PixOffset

        func (p *Alpha) PixOffset(x, y int) int

        PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

        func (*Alpha) RGBA64At

        func (p *Alpha) RGBA64At(x, y int) color.RGBA64

        func (*Alpha) Set

        func (p *Alpha) Set(x, y int, c color.Color)

        func (*Alpha) SetAlpha

        func (p *Alpha) SetAlpha(x, y int, c color.Alpha)

        func (*Alpha) SetRGBA64

        func (p *Alpha) SetRGBA64(x, y int, c color.RGBA64)

        func (*Alpha) SubImage

        func (p *Alpha) SubImage(r Rectangle) Image

        SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

        type Alpha16

        Alpha16 is an in-memory image whose At method returns color.Alpha16 values.

        type Alpha16 struct {
            // Pix holds the image's pixels, as alpha values in big-endian format. The pixel at
            // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*2].
            Pix []uint8
            // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
            Stride int
            // Rect is the image's bounds.
            Rect Rectangle
        }
        

        func NewAlpha16

        func NewAlpha16(r Rectangle) *Alpha16

        NewAlpha16 returns a new Alpha16 image with the given bounds.

        func (*Alpha16) Alpha16At

        func (p *Alpha16) Alpha16At(x, y int) color.Alpha16

        func (*Alpha16) At

        func (p *Alpha16) At(x, y int) color.Color

        func (*Alpha16) Bounds

        func (p *Alpha16) Bounds() Rectangle

        func (*Alpha16) ColorModel

        func (p *Alpha16) ColorModel() color.Model

        func (*Alpha16) Opaque

        func (p *Alpha16) Opaque() bool

        Opaque scans the entire image and reports whether it is fully opaque.

        func (*Alpha16) PixOffset

        func (p *Alpha16) PixOffset(x, y int) int

        PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

        func (*Alpha16) RGBA64At

        func (p *Alpha16) RGBA64At(x, y int) color.RGBA64

        func (*Alpha16) Set

        func (p *Alpha16) Set(x, y int, c color.Color)

        func (*Alpha16) SetAlpha16

        func (p *Alpha16) SetAlpha16(x, y int, c color.Alpha16)

        func (*Alpha16) SetRGBA64

        func (p *Alpha16) SetRGBA64(x, y int, c color.RGBA64)

        func (*Alpha16) SubImage

        func (p *Alpha16) SubImage(r Rectangle) Image

        SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

        type CMYK

        CMYK is an in-memory image whose At method returns color.CMYK values.

        type CMYK struct {
            // Pix holds the image's pixels, in C, M, Y, K order. The pixel at
            // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
            Pix []uint8
            // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
            Stride int
            // Rect is the image's bounds.
            Rect Rectangle
        }
        

        func NewCMYK

        func NewCMYK(r Rectangle) *CMYK

        NewCMYK returns a new CMYK image with the given bounds.

        func (*CMYK) At

        func (p *CMYK) At(x, y int) color.Color

        func (*CMYK) Bounds

        func (p *CMYK) Bounds() Rectangle

        func (*CMYK) CMYKAt

        func (p *CMYK) CMYKAt(x, y int) color.CMYK

        func (*CMYK) ColorModel

        func (p *CMYK) ColorModel() color.Model

        func (*CMYK) Opaque

        func (p *CMYK) Opaque() bool

        Opaque scans the entire image and reports whether it is fully opaque.

        func (*CMYK) PixOffset

        func (p *CMYK) PixOffset(x, y int) int

        PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

        func (*CMYK) RGBA64At

        func (p *CMYK) RGBA64At(x, y int) color.RGBA64

        func (*CMYK) Set

        func (p *CMYK) Set(x, y int, c color.Color)

        func (*CMYK) SetCMYK

        func (p *CMYK) SetCMYK(x, y int, c color.CMYK)

        func (*CMYK) SetRGBA64

        func (p *CMYK) SetRGBA64(x, y int, c color.RGBA64)

        func (*CMYK) SubImage

        func (p *CMYK) SubImage(r Rectangle) Image

        SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

        type Config

        Config holds an image's color model and dimensions.

        type Config struct {
            ColorModel    color.Model
            Width, Height int
        }
        

        func DecodeConfig

        func DecodeConfig(r io.Reader) (Config, string, error)

        DecodeConfig decodes the color model and dimensions of an image that has been encoded in a registered format. The string returned is the format name used during format registration. Format registration is typically done by an init function in the codec-specific package.

        type Gray

        Gray is an in-memory image whose At method returns color.Gray values.

        type Gray struct {
            // Pix holds the image's pixels, as gray values. The pixel at
            // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
            Pix []uint8
            // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
            Stride int
            // Rect is the image's bounds.
            Rect Rectangle
        }
        

        func NewGray

        func NewGray(r Rectangle) *Gray

        NewGray returns a new Gray image with the given bounds.

        func (*Gray) At

        func (p *Gray) At(x, y int) color.Color

        func (*Gray) Bounds

        func (p *Gray) Bounds() Rectangle

        func (*Gray) ColorModel

        func (p *Gray) ColorModel() color.Model

        func (*Gray) GrayAt

        func (p *Gray) GrayAt(x, y int) color.Gray

        func (*Gray) Opaque

        func (p *Gray) Opaque() bool

        Opaque scans the entire image and reports whether it is fully opaque.

        func (*Gray) PixOffset

        func (p *Gray) PixOffset(x, y int) int

        PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

        func (*Gray) RGBA64At

        func (p *Gray) RGBA64At(x, y int) color.RGBA64

        func (*Gray) Set

        func (p *Gray) Set(x, y int, c color.Color)

        func (*Gray) SetGray

        func (p *Gray) SetGray(x, y int, c color.Gray)

        func (*Gray) SetRGBA64

        func (p *Gray) SetRGBA64(x, y int, c color.RGBA64)

        func (*Gray) SubImage

        func (p *Gray) SubImage(r Rectangle) Image

        SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

        type Gray16

        Gray16 is an in-memory image whose At method returns color.Gray16 values.

        type Gray16 struct {
            // Pix holds the image's pixels, as gray values in big-endian format. The pixel at
            // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*2].
            Pix []uint8
            // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
            Stride int
            // Rect is the image's bounds.
            Rect Rectangle
        }
        

        func NewGray16

        func NewGray16(r Rectangle) *Gray16

        NewGray16 returns a new Gray16 image with the given bounds.

        func (*Gray16) At

        func (p *Gray16) At(x, y int) color.Color

        func (*Gray16) Bounds

        func (p *Gray16) Bounds() Rectangle

        func (*Gray16) ColorModel

        func (p *Gray16) ColorModel() color.Model

        func (*Gray16) Gray16At

        func (p *Gray16) Gray16At(x, y int) color.Gray16

        func (*Gray16) Opaque

        func (p *Gray16) Opaque() bool

        Opaque scans the entire image and reports whether it is fully opaque.

        func (*Gray16) PixOffset

        func (p *Gray16) PixOffset(x, y int) int

        PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

        func (*Gray16) RGBA64At

        func (p *Gray16) RGBA64At(x, y int) color.RGBA64

        func (*Gray16) Set

        func (p *Gray16) Set(x, y int, c color.Color)

        func (*Gray16) SetGray16

        func (p *Gray16) SetGray16(x, y int, c color.Gray16)

        func (*Gray16) SetRGBA64

        func (p *Gray16) SetRGBA64(x, y int, c color.RGBA64)

        func (*Gray16) SubImage

        func (p *Gray16) SubImage(r Rectangle) Image

        SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

        type Image

        Image is a finite rectangular grid of color.Color values taken from a color model.

        type Image interface {
            // ColorModel returns the Image's color model.
            ColorModel() color.Model
            // Bounds returns the domain for which At can return non-zero color.
            // The bounds do not necessarily contain the point (0, 0).
            Bounds() Rectangle
            // At returns the color of the pixel at (x, y).
            // At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid.
            // At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one.
            At(x, y int) color.Color
        }

        func Decode

        func Decode(r io.Reader) (Image, string, error)

        Decode decodes an image that has been encoded in a registered format. The string returned is the format name used during format registration. Format registration is typically done by an init function in the codec- specific package.

        type NRGBA

        NRGBA is an in-memory image whose At method returns color.NRGBA values.

        type NRGBA struct {
            // Pix holds the image's pixels, in R, G, B, A order. The pixel at
            // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
            Pix []uint8
            // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
            Stride int
            // Rect is the image's bounds.
            Rect Rectangle
        }
        

        func NewNRGBA

        func NewNRGBA(r Rectangle) *NRGBA

        NewNRGBA returns a new NRGBA image with the given bounds.

        func (*NRGBA) At

        func (p *NRGBA) At(x, y int) color.Color

        func (*NRGBA) Bounds

        func (p *NRGBA) Bounds() Rectangle

        func (*NRGBA) ColorModel

        func (p *NRGBA) ColorModel() color.Model

        func (*NRGBA) NRGBAAt

        func (p *NRGBA) NRGBAAt(x, y int) color.NRGBA

        func (*NRGBA) Opaque

        func (p *NRGBA) Opaque() bool

        Opaque scans the entire image and reports whether it is fully opaque.

        func (*NRGBA) PixOffset

        func (p *NRGBA) PixOffset(x, y int) int

        PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

        func (*NRGBA) RGBA64At

        func (p *NRGBA) RGBA64At(x, y int) color.RGBA64

        func (*NRGBA) Set

        func (p *NRGBA) Set(x, y int, c color.Color)

        func (*NRGBA) SetNRGBA

        func (p *NRGBA) SetNRGBA(x, y int, c color.NRGBA)

        func (*NRGBA) SetRGBA64

        func (p *NRGBA) SetRGBA64(x, y int, c color.RGBA64)

        func (*NRGBA) SubImage

        func (p *NRGBA) SubImage(r Rectangle) Image

        SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

        type NRGBA64

        NRGBA64 is an in-memory image whose At method returns color.NRGBA64 values.

        type NRGBA64 struct {
            // Pix holds the image's pixels, in R, G, B, A order and big-endian format. The pixel at
            // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*8].
            Pix []uint8
            // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
            Stride int
            // Rect is the image's bounds.
            Rect Rectangle
        }
        

        func NewNRGBA64

        func NewNRGBA64(r Rectangle) *NRGBA64

        NewNRGBA64 returns a new NRGBA64 image with the given bounds.

        func (*NRGBA64) At

        func (p *NRGBA64) At(x, y int) color.Color

        func (*NRGBA64) Bounds

        func (p *NRGBA64) Bounds() Rectangle

        func (*NRGBA64) ColorModel

        func (p *NRGBA64) ColorModel() color.Model

        func (*NRGBA64) NRGBA64At

        func (p *NRGBA64) NRGBA64At(x, y int) color.NRGBA64

        func (*NRGBA64) Opaque

        func (p *NRGBA64) Opaque() bool

        Opaque scans the entire image and reports whether it is fully opaque.

        func (*NRGBA64) PixOffset

        func (p *NRGBA64) PixOffset(x, y int) int

        PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

        func (*NRGBA64) RGBA64At

        func (p *NRGBA64) RGBA64At(x, y int) color.RGBA64

        func (*NRGBA64) Set

        func (p *NRGBA64) Set(x, y int, c color.Color)

        func (*NRGBA64) SetNRGBA64

        func (p *NRGBA64) SetNRGBA64(x, y int, c color.NRGBA64)

        func (*NRGBA64) SetRGBA64

        func (p *NRGBA64) SetRGBA64(x, y int, c color.RGBA64)

        func (*NRGBA64) SubImage

        func (p *NRGBA64) SubImage(r Rectangle) Image

        SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

        type NYCbCrA

        NYCbCrA is an in-memory image of non-alpha-premultiplied Y'CbCr-with-alpha colors. A and AStride are analogous to the Y and YStride fields of the embedded YCbCr.

        type NYCbCrA struct {
            YCbCr
            A       []uint8
            AStride int
        }
        

        func NewNYCbCrA

        func NewNYCbCrA(r Rectangle, subsampleRatio YCbCrSubsampleRatio) *NYCbCrA

        NewNYCbCrA returns a new NYCbCrA image with the given bounds and subsample ratio.

        func (*NYCbCrA) AOffset

        func (p *NYCbCrA) AOffset(x, y int) int

        AOffset returns the index of the first element of A that corresponds to the pixel at (x, y).

        func (*NYCbCrA) At

        func (p *NYCbCrA) At(x, y int) color.Color

        func (*NYCbCrA) ColorModel

        func (p *NYCbCrA) ColorModel() color.Model

        func (*NYCbCrA) NYCbCrAAt

        func (p *NYCbCrA) NYCbCrAAt(x, y int) color.NYCbCrA

        func (*NYCbCrA) Opaque

        func (p *NYCbCrA) Opaque() bool

        Opaque scans the entire image and reports whether it is fully opaque.

        func (*NYCbCrA) RGBA64At

        func (p *NYCbCrA) RGBA64At(x, y int) color.RGBA64

        func (*NYCbCrA) SubImage

        func (p *NYCbCrA) SubImage(r Rectangle) Image

        SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

        type Paletted

        Paletted is an in-memory image of uint8 indices into a given palette.

        type Paletted struct {
            // Pix holds the image's pixels, as palette indices. The pixel at
            // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*1].
            Pix []uint8
            // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
            Stride int
            // Rect is the image's bounds.
            Rect Rectangle
            // Palette is the image's palette.
            Palette color.Palette
        }
        

        func NewPaletted

        func NewPaletted(r Rectangle, p color.Palette) *Paletted

        NewPaletted returns a new Paletted image with the given width, height and palette.

        func (*Paletted) At

        func (p *Paletted) At(x, y int) color.Color

        func (*Paletted) Bounds

        func (p *Paletted) Bounds() Rectangle

        func (*Paletted) ColorIndexAt

        func (p *Paletted) ColorIndexAt(x, y int) uint8

        func (*Paletted) ColorModel

        func (p *Paletted) ColorModel() color.Model

        func (*Paletted) Opaque

        func (p *Paletted) Opaque() bool

        Opaque scans the entire image and reports whether it is fully opaque.

        func (*Paletted) PixOffset

        func (p *Paletted) PixOffset(x, y int) int

        PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

        func (*Paletted) RGBA64At

        func (p *Paletted) RGBA64At(x, y int) color.RGBA64

        func (*Paletted) Set

        func (p *Paletted) Set(x, y int, c color.Color)

        func (*Paletted) SetColorIndex

        func (p *Paletted) SetColorIndex(x, y int, index uint8)

        func (*Paletted) SetRGBA64

        func (p *Paletted) SetRGBA64(x, y int, c color.RGBA64)

        func (*Paletted) SubImage

        func (p *Paletted) SubImage(r Rectangle) Image

        SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

        type PalettedImage

        PalettedImage is an image whose colors may come from a limited palette. If m is a PalettedImage and m.ColorModel() returns a color.Palette p, then m.At(x, y) should be equivalent to p[m.ColorIndexAt(x, y)]. If m's color model is not a color.Palette, then ColorIndexAt's behavior is undefined.

        type PalettedImage interface {
            // ColorIndexAt returns the palette index of the pixel at (x, y).
            ColorIndexAt(x, y int) uint8
            Image
        }

        type Point

        A Point is an X, Y coordinate pair. The axes increase right and down.

        type Point struct {
            X, Y int
        }
        

        ZP is the zero Point.

        Deprecated: Use a literal image.Point instead.

        var ZP Point

        func Pt

        func Pt(X, Y int) Point

        Pt is shorthand for Point{X, Y}.

        func (Point) Add

        func (p Point) Add(q Point) Point

        Add returns the vector p+q.

        func (Point) Div

        func (p Point) Div(k int) Point

        Div returns the vector p/k.

        func (Point) Eq

        func (p Point) Eq(q Point) bool

        Eq reports whether p and q are equal.

        func (Point) In

        func (p Point) In(r Rectangle) bool

        In reports whether p is in r.

        func (Point) Mod

        func (p Point) Mod(r Rectangle) Point

        Mod returns the point q in r such that p.X-q.X is a multiple of r's width and p.Y-q.Y is a multiple of r's height.

        func (Point) Mul

        func (p Point) Mul(k int) Point

        Mul returns the vector p*k.

        func (Point) String

        func (p Point) String() string

        String returns a string representation of p like "(3,4)".

        func (Point) Sub

        func (p Point) Sub(q Point) Point

        Sub returns the vector p-q.

        type RGBA

        RGBA is an in-memory image whose At method returns color.RGBA values.

        type RGBA struct {
            // Pix holds the image's pixels, in R, G, B, A order. The pixel at
            // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
            Pix []uint8
            // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
            Stride int
            // Rect is the image's bounds.
            Rect Rectangle
        }
        

        func NewRGBA

        func NewRGBA(r Rectangle) *RGBA

        NewRGBA returns a new RGBA image with the given bounds.

        func (*RGBA) At

        func (p *RGBA) At(x, y int) color.Color

        func (*RGBA) Bounds

        func (p *RGBA) Bounds() Rectangle

        func (*RGBA) ColorModel

        func (p *RGBA) ColorModel() color.Model

        func (*RGBA) Opaque

        func (p *RGBA) Opaque() bool

        Opaque scans the entire image and reports whether it is fully opaque.

        func (*RGBA) PixOffset

        func (p *RGBA) PixOffset(x, y int) int

        PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

        func (*RGBA) RGBA64At

        func (p *RGBA) RGBA64At(x, y int) color.RGBA64

        func (*RGBA) RGBAAt

        func (p *RGBA) RGBAAt(x, y int) color.RGBA

        func (*RGBA) Set

        func (p *RGBA) Set(x, y int, c color.Color)

        func (*RGBA) SetRGBA

        func (p *RGBA) SetRGBA(x, y int, c color.RGBA)

        func (*RGBA) SetRGBA64

        func (p *RGBA) SetRGBA64(x, y int, c color.RGBA64)

        func (*RGBA) SubImage

        func (p *RGBA) SubImage(r Rectangle) Image

        SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

        type RGBA64

        RGBA64 is an in-memory image whose At method returns color.RGBA64 values.

        type RGBA64 struct {
            // Pix holds the image's pixels, in R, G, B, A order and big-endian format. The pixel at
            // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*8].
            Pix []uint8
            // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
            Stride int
            // Rect is the image's bounds.
            Rect Rectangle
        }
        

        func NewRGBA64

        func NewRGBA64(r Rectangle) *RGBA64

        NewRGBA64 returns a new RGBA64 image with the given bounds.

        func (*RGBA64) At

        func (p *RGBA64) At(x, y int) color.Color

        func (*RGBA64) Bounds

        func (p *RGBA64) Bounds() Rectangle

        func (*RGBA64) ColorModel

        func (p *RGBA64) ColorModel() color.Model

        func (*RGBA64) Opaque

        func (p *RGBA64) Opaque() bool

        Opaque scans the entire image and reports whether it is fully opaque.

        func (*RGBA64) PixOffset

        func (p *RGBA64) PixOffset(x, y int) int

        PixOffset returns the index of the first element of Pix that corresponds to the pixel at (x, y).

        func (*RGBA64) RGBA64At

        func (p *RGBA64) RGBA64At(x, y int) color.RGBA64

        func (*RGBA64) Set

        func (p *RGBA64) Set(x, y int, c color.Color)

        func (*RGBA64) SetRGBA64

        func (p *RGBA64) SetRGBA64(x, y int, c color.RGBA64)

        func (*RGBA64) SubImage

        func (p *RGBA64) SubImage(r Rectangle) Image

        SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

        type RGBA64Image

        RGBA64Image is an Image whose pixels can be converted directly to a color.RGBA64.

        type RGBA64Image interface {
            // RGBA64At returns the RGBA64 color of the pixel at (x, y). It is
            // equivalent to calling At(x, y).RGBA() and converting the resulting
            // 32-bit return values to a color.RGBA64, but it can avoid allocations
            // from converting concrete color types to the color.Color interface type.
            RGBA64At(x, y int) color.RGBA64
            Image
        }

        type Rectangle

        A Rectangle contains the points with Min.X <= X < Max.X, Min.Y <= Y < Max.Y. It is well-formed if Min.X <= Max.X and likewise for Y. Points are always well-formed. A rectangle's methods always return well-formed outputs for well-formed inputs.

        A Rectangle is also an Image whose bounds are the rectangle itself. At returns color.Opaque for points in the rectangle and color.Transparent otherwise.

        type Rectangle struct {
            Min, Max Point
        }
        

        ZR is the zero Rectangle.

        Deprecated: Use a literal image.Rectangle instead.

        var ZR Rectangle

        func Rect

        func Rect(x0, y0, x1, y1 int) Rectangle

        Rect is shorthand for Rectangle{Pt(x0, y0), Pt(x1, y1)}. The returned rectangle has minimum and maximum coordinates swapped if necessary so that it is well-formed.

        func (Rectangle) Add

        func (r Rectangle) Add(p Point) Rectangle

        Add returns the rectangle r translated by p.

        func (Rectangle) At

        func (r Rectangle) At(x, y int) color.Color

        At implements the Image interface.

        func (Rectangle) Bounds

        func (r Rectangle) Bounds() Rectangle

        Bounds implements the Image interface.

        func (Rectangle) Canon

        func (r Rectangle) Canon() Rectangle

        Canon returns the canonical version of r. The returned rectangle has minimum and maximum coordinates swapped if necessary so that it is well-formed.

        func (Rectangle) ColorModel

        func (r Rectangle) ColorModel() color.Model

        ColorModel implements the Image interface.

        func (Rectangle) Dx

        func (r Rectangle) Dx() int

        Dx returns r's width.

        func (Rectangle) Dy

        func (r Rectangle) Dy() int

        Dy returns r's height.

        func (Rectangle) Empty

        func (r Rectangle) Empty() bool

        Empty reports whether the rectangle contains no points.

        func (Rectangle) Eq

        func (r Rectangle) Eq(s Rectangle) bool

        Eq reports whether r and s contain the same set of points. All empty rectangles are considered equal.

        func (Rectangle) In

        func (r Rectangle) In(s Rectangle) bool

        In reports whether every point in r is in s.

        func (Rectangle) Inset

        func (r Rectangle) Inset(n int) Rectangle

        Inset returns the rectangle r inset by n, which may be negative. If either of r's dimensions is less than 2*n then an empty rectangle near the center of r will be returned.

        func (Rectangle) Intersect

        func (r Rectangle) Intersect(s Rectangle) Rectangle

        Intersect returns the largest rectangle contained by both r and s. If the two rectangles do not overlap then the zero rectangle will be returned.

        func (Rectangle) Overlaps

        func (r Rectangle) Overlaps(s Rectangle) bool

        Overlaps reports whether r and s have a non-empty intersection.

        func (Rectangle) RGBA64At

        func (r Rectangle) RGBA64At(x, y int) color.RGBA64

        RGBA64At implements the RGBA64Image interface.

        func (Rectangle) Size

        func (r Rectangle) Size() Point

        Size returns r's width and height.

        func (Rectangle) String

        func (r Rectangle) String() string

        String returns a string representation of r like "(3,4)-(6,5)".

        func (Rectangle) Sub

        func (r Rectangle) Sub(p Point) Rectangle

        Sub returns the rectangle r translated by -p.

        func (Rectangle) Union

        func (r Rectangle) Union(s Rectangle) Rectangle

        Union returns the smallest rectangle that contains both r and s.

        type Uniform

        Uniform is an infinite-sized Image of uniform color. It implements the color.Color, color.Model, and Image interfaces.

        type Uniform struct {
            C color.Color
        }
        

        func NewUniform

        func NewUniform(c color.Color) *Uniform

        NewUniform returns a new Uniform image of the given color.

        func (*Uniform) At

        func (c *Uniform) At(x, y int) color.Color

        func (*Uniform) Bounds

        func (c *Uniform) Bounds() Rectangle

        func (*Uniform) ColorModel

        func (c *Uniform) ColorModel() color.Model

        func (*Uniform) Convert

        func (c *Uniform) Convert(color.Color) color.Color

        func (*Uniform) Opaque

        func (c *Uniform) Opaque() bool

        Opaque scans the entire image and reports whether it is fully opaque.

        func (*Uniform) RGBA

        func (c *Uniform) RGBA() (r, g, b, a uint32)

        func (*Uniform) RGBA64At

        func (c *Uniform) RGBA64At(x, y int) color.RGBA64

        type YCbCr

        YCbCr is an in-memory image of Y'CbCr colors. There is one Y sample per pixel, but each Cb and Cr sample can span one or more pixels. YStride is the Y slice index delta between vertically adjacent pixels. CStride is the Cb and Cr slice index delta between vertically adjacent pixels that map to separate chroma samples. It is not an absolute requirement, but YStride and len(Y) are typically multiples of 8, and:

        For 4:4:4, CStride == YStride/1 && len(Cb) == len(Cr) == len(Y)/1.
        For 4:2:2, CStride == YStride/2 && len(Cb) == len(Cr) == len(Y)/2.
        For 4:2:0, CStride == YStride/2 && len(Cb) == len(Cr) == len(Y)/4.
        For 4:4:0, CStride == YStride/1 && len(Cb) == len(Cr) == len(Y)/2.
        For 4:1:1, CStride == YStride/4 && len(Cb) == len(Cr) == len(Y)/4.
        For 4:1:0, CStride == YStride/4 && len(Cb) == len(Cr) == len(Y)/8.
        
        type YCbCr struct {
            Y, Cb, Cr      []uint8
            YStride        int
            CStride        int
            SubsampleRatio YCbCrSubsampleRatio
            Rect           Rectangle
        }
        

        func NewYCbCr

        func NewYCbCr(r Rectangle, subsampleRatio YCbCrSubsampleRatio) *YCbCr

        NewYCbCr returns a new YCbCr image with the given bounds and subsample ratio.

        func (*YCbCr) At

        func (p *YCbCr) At(x, y int) color.Color

        func (*YCbCr) Bounds

        func (p *YCbCr) Bounds() Rectangle

        func (*YCbCr) COffset

        func (p *YCbCr) COffset(x, y int) int

        COffset returns the index of the first element of Cb or Cr that corresponds to the pixel at (x, y).

        func (*YCbCr) ColorModel

        func (p *YCbCr) ColorModel() color.Model

        func (*YCbCr) Opaque

        func (p *YCbCr) Opaque() bool

        func (*YCbCr) RGBA64At

        func (p *YCbCr) RGBA64At(x, y int) color.RGBA64

        func (*YCbCr) SubImage

        func (p *YCbCr) SubImage(r Rectangle) Image

        SubImage returns an image representing the portion of the image p visible through r. The returned value shares pixels with the original image.

        func (*YCbCr) YCbCrAt

        func (p *YCbCr) YCbCrAt(x, y int) color.YCbCr

        func (*YCbCr) YOffset

        func (p *YCbCr) YOffset(x, y int) int

        YOffset returns the index of the first element of Y that corresponds to the pixel at (x, y).

        type YCbCrSubsampleRatio

        YCbCrSubsampleRatio is the chroma subsample ratio used in a YCbCr image.

        type YCbCrSubsampleRatio int
        const (
            YCbCrSubsampleRatio444 YCbCrSubsampleRatio = iota
            YCbCrSubsampleRatio422
            YCbCrSubsampleRatio420
            YCbCrSubsampleRatio440
            YCbCrSubsampleRatio411
            YCbCrSubsampleRatio410
        )

        func (YCbCrSubsampleRatio) String

        func (s YCbCrSubsampleRatio) String() string

        Subdirectories

        Name Synopsis
        ..
        color Package color implements a basic color library.
        palette Package palette provides standard color palettes.
        draw Package draw provides image composition functions.
        gif Package gif implements a GIF image decoder and encoder.
        jpeg Package jpeg implements a JPEG image decoder and encoder.
        png Package png implements a PNG image decoder and encoder.
        color - Go Documentation Server
        ...

        Package color

        import "image/color"
        Overview
        Index
        Subdirectories

        Overview ▾

        Package color implements a basic color library.

        Variables

        Standard colors.

        var (
            Black       = Gray16{0}
            White       = Gray16{0xffff}
            Transparent = Alpha16{0}
            Opaque      = Alpha16{0xffff}
        )

        func CMYKToRGB

        func CMYKToRGB(c, m, y, k uint8) (uint8, uint8, uint8)

        CMYKToRGB converts a CMYK quadruple to an RGB triple.

        func RGBToCMYK

        func RGBToCMYK(r, g, b uint8) (uint8, uint8, uint8, uint8)

        RGBToCMYK converts an RGB triple to a CMYK quadruple.

        func RGBToYCbCr

        func RGBToYCbCr(r, g, b uint8) (uint8, uint8, uint8)

        RGBToYCbCr converts an RGB triple to a Y'CbCr triple.

        func YCbCrToRGB

        func YCbCrToRGB(y, cb, cr uint8) (uint8, uint8, uint8)

        YCbCrToRGB converts a Y'CbCr triple to an RGB triple.

        type Alpha

        Alpha represents an 8-bit alpha color.

        type Alpha struct {
            A uint8
        }
        

        func (Alpha) RGBA

        func (c Alpha) RGBA() (r, g, b, a uint32)

        type Alpha16

        Alpha16 represents a 16-bit alpha color.

        type Alpha16 struct {
            A uint16
        }
        

        func (Alpha16) RGBA

        func (c Alpha16) RGBA() (r, g, b, a uint32)

        type CMYK

        CMYK represents a fully opaque CMYK color, having 8 bits for each of cyan, magenta, yellow and black.

        It is not associated with any particular color profile.

        type CMYK struct {
            C, M, Y, K uint8
        }
        

        func (CMYK) RGBA

        func (c CMYK) RGBA() (uint32, uint32, uint32, uint32)

        type Color

        Color can convert itself to alpha-premultiplied 16-bits per channel RGBA. The conversion may be lossy.

        type Color interface {
            // RGBA returns the alpha-premultiplied red, green, blue and alpha values
            // for the color. Each value ranges within [0, 0xffff], but is represented
            // by a uint32 so that multiplying by a blend factor up to 0xffff will not
            // overflow.
            //
            // An alpha-premultiplied color component c has been scaled by alpha (a),
            // so has valid values 0 <= c <= a.
            RGBA() (r, g, b, a uint32)
        }

        type Gray

        Gray represents an 8-bit grayscale color.

        type Gray struct {
            Y uint8
        }
        

        func (Gray) RGBA

        func (c Gray) RGBA() (r, g, b, a uint32)

        type Gray16

        Gray16 represents a 16-bit grayscale color.

        type Gray16 struct {
            Y uint16
        }
        

        func (Gray16) RGBA

        func (c Gray16) RGBA() (r, g, b, a uint32)

        type Model

        Model can convert any Color to one from its own color model. The conversion may be lossy.

        type Model interface {
            Convert(c Color) Color
        }

        Models for the standard color types.

        var (
            RGBAModel    Model = ModelFunc(rgbaModel)
            RGBA64Model  Model = ModelFunc(rgba64Model)
            NRGBAModel   Model = ModelFunc(nrgbaModel)
            NRGBA64Model Model = ModelFunc(nrgba64Model)
            AlphaModel   Model = ModelFunc(alphaModel)
            Alpha16Model Model = ModelFunc(alpha16Model)
            GrayModel    Model = ModelFunc(grayModel)
            Gray16Model  Model = ModelFunc(gray16Model)
        )

        CMYKModel is the Model for CMYK colors.

        var CMYKModel Model = ModelFunc(cmykModel)

        NYCbCrAModel is the Model for non-alpha-premultiplied Y'CbCr-with-alpha colors.

        var NYCbCrAModel Model = ModelFunc(nYCbCrAModel)

        YCbCrModel is the Model for Y'CbCr colors.

        var YCbCrModel Model = ModelFunc(yCbCrModel)

        func ModelFunc

        func ModelFunc(f func(Color) Color) Model

        ModelFunc returns a Model that invokes f to implement the conversion.

        type NRGBA

        NRGBA represents a non-alpha-premultiplied 32-bit color.

        type NRGBA struct {
            R, G, B, A uint8
        }
        

        func (NRGBA) RGBA

        func (c NRGBA) RGBA() (r, g, b, a uint32)

        type NRGBA64

        NRGBA64 represents a non-alpha-premultiplied 64-bit color, having 16 bits for each of red, green, blue and alpha.

        type NRGBA64 struct {
            R, G, B, A uint16
        }
        

        func (NRGBA64) RGBA

        func (c NRGBA64) RGBA() (r, g, b, a uint32)

        type NYCbCrA

        NYCbCrA represents a non-alpha-premultiplied Y'CbCr-with-alpha color, having 8 bits each for one luma, two chroma and one alpha component.

        type NYCbCrA struct {
            YCbCr
            A uint8
        }
        

        func (NYCbCrA) RGBA

        func (c NYCbCrA) RGBA() (uint32, uint32, uint32, uint32)

        type Palette

        Palette is a palette of colors.

        type Palette []Color

        func (Palette) Convert

        func (p Palette) Convert(c Color) Color

        Convert returns the palette color closest to c in Euclidean R,G,B space.

        func (Palette) Index

        func (p Palette) Index(c Color) int

        Index returns the index of the palette color closest to c in Euclidean R,G,B,A space.

        type RGBA

        RGBA represents a traditional 32-bit alpha-premultiplied color, having 8 bits for each of red, green, blue and alpha.

        An alpha-premultiplied color component C has been scaled by alpha (A), so has valid values 0 <= C <= A.

        type RGBA struct {
            R, G, B, A uint8
        }
        

        func (RGBA) RGBA

        func (c RGBA) RGBA() (r, g, b, a uint32)

        type RGBA64

        RGBA64 represents a 64-bit alpha-premultiplied color, having 16 bits for each of red, green, blue and alpha.

        An alpha-premultiplied color component C has been scaled by alpha (A), so has valid values 0 <= C <= A.

        type RGBA64 struct {
            R, G, B, A uint16
        }
        

        func (RGBA64) RGBA

        func (c RGBA64) RGBA() (r, g, b, a uint32)

        type YCbCr

        YCbCr represents a fully opaque 24-bit Y'CbCr color, having 8 bits each for one luma and two chroma components.

        JPEG, VP8, the MPEG family and other codecs use this color model. Such codecs often use the terms YUV and Y'CbCr interchangeably, but strictly speaking, the term YUV applies only to analog video signals, and Y' (luma) is Y (luminance) after applying gamma correction.

        Conversion between RGB and Y'CbCr is lossy and there are multiple, slightly different formulae for converting between the two. This package follows the JFIF specification at https://www.w3.org/Graphics/JPEG/jfif3.pdf.

        type YCbCr struct {
            Y, Cb, Cr uint8
        }
        

        func (YCbCr) RGBA

        func (c YCbCr) RGBA() (uint32, uint32, uint32, uint32)

        Subdirectories

        Name Synopsis
        ..
        palette Package palette provides standard color palettes.
        palette - Go Documentation Server
        ...

        Package palette

        import "image/color/palette"
        Overview
        Index

        Overview ▾

        Package palette provides standard color palettes.

        Index ▾

        Package files

        generate.go palette.go

        Variables

        Plan9 is a 256-color palette that partitions the 24-bit RGB space into 4×4×4 subdivision, with 4 shades in each subcube. Compared to the WebSafe, the idea is to reduce the color resolution by dicing the color cube into fewer cells, and to use the extra space to increase the intensity resolution. This results in 16 gray shades (4 gray subcubes with 4 samples in each), 13 shades of each primary and secondary color (3 subcubes with 4 samples plus black) and a reasonable selection of colors covering the rest of the color cube. The advantage is better representation of continuous tones.

        This palette was used in the Plan 9 Operating System, described at https://9p.io/magic/man2html/6/color

        var Plan9 = []color.Color{
            color.RGBA{0x00, 0x00, 0x00, 0xff},
            color.RGBA{0x00, 0x00, 0x44, 0xff},
            color.RGBA{0x00, 0x00, 0x88, 0xff},
            color.RGBA{0x00, 0x00, 0xcc, 0xff},
            color.RGBA{0x00, 0x44, 0x00, 0xff},
            color.RGBA{0x00, 0x44, 0x44, 0xff},
            color.RGBA{0x00, 0x44, 0x88, 0xff},
            color.RGBA{0x00, 0x44, 0xcc, 0xff},
            color.RGBA{0x00, 0x88, 0x00, 0xff},
            color.RGBA{0x00, 0x88, 0x44, 0xff},
            color.RGBA{0x00, 0x88, 0x88, 0xff},
            color.RGBA{0x00, 0x88, 0xcc, 0xff},
            color.RGBA{0x00, 0xcc, 0x00, 0xff},
            color.RGBA{0x00, 0xcc, 0x44, 0xff},
            color.RGBA{0x00, 0xcc, 0x88, 0xff},
            color.RGBA{0x00, 0xcc, 0xcc, 0xff},
            color.RGBA{0x00, 0xdd, 0xdd, 0xff},
            color.RGBA{0x11, 0x11, 0x11, 0xff},
            color.RGBA{0x00, 0x00, 0x55, 0xff},
            color.RGBA{0x00, 0x00, 0x99, 0xff},
            color.RGBA{0x00, 0x00, 0xdd, 0xff},
            color.RGBA{0x00, 0x55, 0x00, 0xff},
            color.RGBA{0x00, 0x55, 0x55, 0xff},
            color.RGBA{0x00, 0x4c, 0x99, 0xff},
            color.RGBA{0x00, 0x49, 0xdd, 0xff},
            color.RGBA{0x00, 0x99, 0x00, 0xff},
            color.RGBA{0x00, 0x99, 0x4c, 0xff},
            color.RGBA{0x00, 0x99, 0x99, 0xff},
            color.RGBA{0x00, 0x93, 0xdd, 0xff},
            color.RGBA{0x00, 0xdd, 0x00, 0xff},
            color.RGBA{0x00, 0xdd, 0x49, 0xff},
            color.RGBA{0x00, 0xdd, 0x93, 0xff},
            color.RGBA{0x00, 0xee, 0x9e, 0xff},
            color.RGBA{0x00, 0xee, 0xee, 0xff},
            color.RGBA{0x22, 0x22, 0x22, 0xff},
            color.RGBA{0x00, 0x00, 0x66, 0xff},
            color.RGBA{0x00, 0x00, 0xaa, 0xff},
            color.RGBA{0x00, 0x00, 0xee, 0xff},
            color.RGBA{0x00, 0x66, 0x00, 0xff},
            color.RGBA{0x00, 0x66, 0x66, 0xff},
            color.RGBA{0x00, 0x55, 0xaa, 0xff},
            color.RGBA{0x00, 0x4f, 0xee, 0xff},
            color.RGBA{0x00, 0xaa, 0x00, 0xff},
            color.RGBA{0x00, 0xaa, 0x55, 0xff},
            color.RGBA{0x00, 0xaa, 0xaa, 0xff},
            color.RGBA{0x00, 0x9e, 0xee, 0xff},
            color.RGBA{0x00, 0xee, 0x00, 0xff},
            color.RGBA{0x00, 0xee, 0x4f, 0xff},
            color.RGBA{0x00, 0xff, 0x55, 0xff},
            color.RGBA{0x00, 0xff, 0xaa, 0xff},
            color.RGBA{0x00, 0xff, 0xff, 0xff},
            color.RGBA{0x33, 0x33, 0x33, 0xff},
            color.RGBA{0x00, 0x00, 0x77, 0xff},
            color.RGBA{0x00, 0x00, 0xbb, 0xff},
            color.RGBA{0x00, 0x00, 0xff, 0xff},
            color.RGBA{0x00, 0x77, 0x00, 0xff},
            color.RGBA{0x00, 0x77, 0x77, 0xff},
            color.RGBA{0x00, 0x5d, 0xbb, 0xff},
            color.RGBA{0x00, 0x55, 0xff, 0xff},
            color.RGBA{0x00, 0xbb, 0x00, 0xff},
            color.RGBA{0x00, 0xbb, 0x5d, 0xff},
            color.RGBA{0x00, 0xbb, 0xbb, 0xff},
            color.RGBA{0x00, 0xaa, 0xff, 0xff},
            color.RGBA{0x00, 0xff, 0x00, 0xff},
            color.RGBA{0x44, 0x00, 0x44, 0xff},
            color.RGBA{0x44, 0x00, 0x88, 0xff},
            color.RGBA{0x44, 0x00, 0xcc, 0xff},
            color.RGBA{0x44, 0x44, 0x00, 0xff},
            color.RGBA{0x44, 0x44, 0x44, 0xff},
            color.RGBA{0x44, 0x44, 0x88, 0xff},
            color.RGBA{0x44, 0x44, 0xcc, 0xff},
            color.RGBA{0x44, 0x88, 0x00, 0xff},
            color.RGBA{0x44, 0x88, 0x44, 0xff},
            color.RGBA{0x44, 0x88, 0x88, 0xff},
            color.RGBA{0x44, 0x88, 0xcc, 0xff},
            color.RGBA{0x44, 0xcc, 0x00, 0xff},
            color.RGBA{0x44, 0xcc, 0x44, 0xff},
            color.RGBA{0x44, 0xcc, 0x88, 0xff},
            color.RGBA{0x44, 0xcc, 0xcc, 0xff},
            color.RGBA{0x44, 0x00, 0x00, 0xff},
            color.RGBA{0x55, 0x00, 0x00, 0xff},
            color.RGBA{0x55, 0x00, 0x55, 0xff},
            color.RGBA{0x4c, 0x00, 0x99, 0xff},
            color.RGBA{0x49, 0x00, 0xdd, 0xff},
            color.RGBA{0x55, 0x55, 0x00, 0xff},
            color.RGBA{0x55, 0x55, 0x55, 0xff},
            color.RGBA{0x4c, 0x4c, 0x99, 0xff},
            color.RGBA{0x49, 0x49, 0xdd, 0xff},
            color.RGBA{0x4c, 0x99, 0x00, 0xff},
            color.RGBA{0x4c, 0x99, 0x4c, 0xff},
            color.RGBA{0x4c, 0x99, 0x99, 0xff},
            color.RGBA{0x49, 0x93, 0xdd, 0xff},
            color.RGBA{0x49, 0xdd, 0x00, 0xff},
            color.RGBA{0x49, 0xdd, 0x49, 0xff},
            color.RGBA{0x49, 0xdd, 0x93, 0xff},
            color.RGBA{0x49, 0xdd, 0xdd, 0xff},
            color.RGBA{0x4f, 0xee, 0xee, 0xff},
            color.RGBA{0x66, 0x00, 0x00, 0xff},
            color.RGBA{0x66, 0x00, 0x66, 0xff},
            color.RGBA{0x55, 0x00, 0xaa, 0xff},
            color.RGBA{0x4f, 0x00, 0xee, 0xff},
            color.RGBA{0x66, 0x66, 0x00, 0xff},
            color.RGBA{0x66, 0x66, 0x66, 0xff},
            color.RGBA{0x55, 0x55, 0xaa, 0xff},
            color.RGBA{0x4f, 0x4f, 0xee, 0xff},
            color.RGBA{0x55, 0xaa, 0x00, 0xff},
            color.RGBA{0x55, 0xaa, 0x55, 0xff},
            color.RGBA{0x55, 0xaa, 0xaa, 0xff},
            color.RGBA{0x4f, 0x9e, 0xee, 0xff},
            color.RGBA{0x4f, 0xee, 0x00, 0xff},
            color.RGBA{0x4f, 0xee, 0x4f, 0xff},
            color.RGBA{0x4f, 0xee, 0x9e, 0xff},
            color.RGBA{0x55, 0xff, 0xaa, 0xff},
            color.RGBA{0x55, 0xff, 0xff, 0xff},
            color.RGBA{0x77, 0x00, 0x00, 0xff},
            color.RGBA{0x77, 0x00, 0x77, 0xff},
            color.RGBA{0x5d, 0x00, 0xbb, 0xff},
            color.RGBA{0x55, 0x00, 0xff, 0xff},
            color.RGBA{0x77, 0x77, 0x00, 0xff},
            color.RGBA{0x77, 0x77, 0x77, 0xff},
            color.RGBA{0x5d, 0x5d, 0xbb, 0xff},
            color.RGBA{0x55, 0x55, 0xff, 0xff},
            color.RGBA{0x5d, 0xbb, 0x00, 0xff},
            color.RGBA{0x5d, 0xbb, 0x5d, 0xff},
            color.RGBA{0x5d, 0xbb, 0xbb, 0xff},
            color.RGBA{0x55, 0xaa, 0xff, 0xff},
            color.RGBA{0x55, 0xff, 0x00, 0xff},
            color.RGBA{0x55, 0xff, 0x55, 0xff},
            color.RGBA{0x88, 0x00, 0x88, 0xff},
            color.RGBA{0x88, 0x00, 0xcc, 0xff},
            color.RGBA{0x88, 0x44, 0x00, 0xff},
            color.RGBA{0x88, 0x44, 0x44, 0xff},
            color.RGBA{0x88, 0x44, 0x88, 0xff},
            color.RGBA{0x88, 0x44, 0xcc, 0xff},
            color.RGBA{0x88, 0x88, 0x00, 0xff},
            color.RGBA{0x88, 0x88, 0x44, 0xff},
            color.RGBA{0x88, 0x88, 0x88, 0xff},
            color.RGBA{0x88, 0x88, 0xcc, 0xff},
            color.RGBA{0x88, 0xcc, 0x00, 0xff},
            color.RGBA{0x88, 0xcc, 0x44, 0xff},
            color.RGBA{0x88, 0xcc, 0x88, 0xff},
            color.RGBA{0x88, 0xcc, 0xcc, 0xff},
            color.RGBA{0x88, 0x00, 0x00, 0xff},
            color.RGBA{0x88, 0x00, 0x44, 0xff},
            color.RGBA{0x99, 0x00, 0x4c, 0xff},
            color.RGBA{0x99, 0x00, 0x99, 0xff},
            color.RGBA{0x93, 0x00, 0xdd, 0xff},
            color.RGBA{0x99, 0x4c, 0x00, 0xff},
            color.RGBA{0x99, 0x4c, 0x4c, 0xff},
            color.RGBA{0x99, 0x4c, 0x99, 0xff},
            color.RGBA{0x93, 0x49, 0xdd, 0xff},
            color.RGBA{0x99, 0x99, 0x00, 0xff},
            color.RGBA{0x99, 0x99, 0x4c, 0xff},
            color.RGBA{0x99, 0x99, 0x99, 0xff},
            color.RGBA{0x93, 0x93, 0xdd, 0xff},
            color.RGBA{0x93, 0xdd, 0x00, 0xff},
            color.RGBA{0x93, 0xdd, 0x49, 0xff},
            color.RGBA{0x93, 0xdd, 0x93, 0xff},
            color.RGBA{0x93, 0xdd, 0xdd, 0xff},
            color.RGBA{0x99, 0x00, 0x00, 0xff},
            color.RGBA{0xaa, 0x00, 0x00, 0xff},
            color.RGBA{0xaa, 0x00, 0x55, 0xff},
            color.RGBA{0xaa, 0x00, 0xaa, 0xff},
            color.RGBA{0x9e, 0x00, 0xee, 0xff},
            color.RGBA{0xaa, 0x55, 0x00, 0xff},
            color.RGBA{0xaa, 0x55, 0x55, 0xff},
            color.RGBA{0xaa, 0x55, 0xaa, 0xff},
            color.RGBA{0x9e, 0x4f, 0xee, 0xff},
            color.RGBA{0xaa, 0xaa, 0x00, 0xff},
            color.RGBA{0xaa, 0xaa, 0x55, 0xff},
            color.RGBA{0xaa, 0xaa, 0xaa, 0xff},
            color.RGBA{0x9e, 0x9e, 0xee, 0xff},
            color.RGBA{0x9e, 0xee, 0x00, 0xff},
            color.RGBA{0x9e, 0xee, 0x4f, 0xff},
            color.RGBA{0x9e, 0xee, 0x9e, 0xff},
            color.RGBA{0x9e, 0xee, 0xee, 0xff},
            color.RGBA{0xaa, 0xff, 0xff, 0xff},
            color.RGBA{0xbb, 0x00, 0x00, 0xff},
            color.RGBA{0xbb, 0x00, 0x5d, 0xff},
            color.RGBA{0xbb, 0x00, 0xbb, 0xff},
            color.RGBA{0xaa, 0x00, 0xff, 0xff},
            color.RGBA{0xbb, 0x5d, 0x00, 0xff},
            color.RGBA{0xbb, 0x5d, 0x5d, 0xff},
            color.RGBA{0xbb, 0x5d, 0xbb, 0xff},
            color.RGBA{0xaa, 0x55, 0xff, 0xff},
            color.RGBA{0xbb, 0xbb, 0x00, 0xff},
            color.RGBA{0xbb, 0xbb, 0x5d, 0xff},
            color.RGBA{0xbb, 0xbb, 0xbb, 0xff},
            color.RGBA{0xaa, 0xaa, 0xff, 0xff},
            color.RGBA{0xaa, 0xff, 0x00, 0xff},
            color.RGBA{0xaa, 0xff, 0x55, 0xff},
            color.RGBA{0xaa, 0xff, 0xaa, 0xff},
            color.RGBA{0xcc, 0x00, 0xcc, 0xff},
            color.RGBA{0xcc, 0x44, 0x00, 0xff},
            color.RGBA{0xcc, 0x44, 0x44, 0xff},
            color.RGBA{0xcc, 0x44, 0x88, 0xff},
            color.RGBA{0xcc, 0x44, 0xcc, 0xff},
            color.RGBA{0xcc, 0x88, 0x00, 0xff},
            color.RGBA{0xcc, 0x88, 0x44, 0xff},
            color.RGBA{0xcc, 0x88, 0x88, 0xff},
            color.RGBA{0xcc, 0x88, 0xcc, 0xff},
            color.RGBA{0xcc, 0xcc, 0x00, 0xff},
            color.RGBA{0xcc, 0xcc, 0x44, 0xff},
            color.RGBA{0xcc, 0xcc, 0x88, 0xff},
            color.RGBA{0xcc, 0xcc, 0xcc, 0xff},
            color.RGBA{0xcc, 0x00, 0x00, 0xff},
            color.RGBA{0xcc, 0x00, 0x44, 0xff},
            color.RGBA{0xcc, 0x00, 0x88, 0xff},
            color.RGBA{0xdd, 0x00, 0x93, 0xff},
            color.RGBA{0xdd, 0x00, 0xdd, 0xff},
            color.RGBA{0xdd, 0x49, 0x00, 0xff},
            color.RGBA{0xdd, 0x49, 0x49, 0xff},
            color.RGBA{0xdd, 0x49, 0x93, 0xff},
            color.RGBA{0xdd, 0x49, 0xdd, 0xff},
            color.RGBA{0xdd, 0x93, 0x00, 0xff},
            color.RGBA{0xdd, 0x93, 0x49, 0xff},
            color.RGBA{0xdd, 0x93, 0x93, 0xff},
            color.RGBA{0xdd, 0x93, 0xdd, 0xff},
            color.RGBA{0xdd, 0xdd, 0x00, 0xff},
            color.RGBA{0xdd, 0xdd, 0x49, 0xff},
            color.RGBA{0xdd, 0xdd, 0x93, 0xff},
            color.RGBA{0xdd, 0xdd, 0xdd, 0xff},
            color.RGBA{0xdd, 0x00, 0x00, 0xff},
            color.RGBA{0xdd, 0x00, 0x49, 0xff},
            color.RGBA{0xee, 0x00, 0x4f, 0xff},
            color.RGBA{0xee, 0x00, 0x9e, 0xff},
            color.RGBA{0xee, 0x00, 0xee, 0xff},
            color.RGBA{0xee, 0x4f, 0x00, 0xff},
            color.RGBA{0xee, 0x4f, 0x4f, 0xff},
            color.RGBA{0xee, 0x4f, 0x9e, 0xff},
            color.RGBA{0xee, 0x4f, 0xee, 0xff},
            color.RGBA{0xee, 0x9e, 0x00, 0xff},
            color.RGBA{0xee, 0x9e, 0x4f, 0xff},
            color.RGBA{0xee, 0x9e, 0x9e, 0xff},
            color.RGBA{0xee, 0x9e, 0xee, 0xff},
            color.RGBA{0xee, 0xee, 0x00, 0xff},
            color.RGBA{0xee, 0xee, 0x4f, 0xff},
            color.RGBA{0xee, 0xee, 0x9e, 0xff},
            color.RGBA{0xee, 0xee, 0xee, 0xff},
            color.RGBA{0xee, 0x00, 0x00, 0xff},
            color.RGBA{0xff, 0x00, 0x00, 0xff},
            color.RGBA{0xff, 0x00, 0x55, 0xff},
            color.RGBA{0xff, 0x00, 0xaa, 0xff},
            color.RGBA{0xff, 0x00, 0xff, 0xff},
            color.RGBA{0xff, 0x55, 0x00, 0xff},
            color.RGBA{0xff, 0x55, 0x55, 0xff},
            color.RGBA{0xff, 0x55, 0xaa, 0xff},
            color.RGBA{0xff, 0x55, 0xff, 0xff},
            color.RGBA{0xff, 0xaa, 0x00, 0xff},
            color.RGBA{0xff, 0xaa, 0x55, 0xff},
            color.RGBA{0xff, 0xaa, 0xaa, 0xff},
            color.RGBA{0xff, 0xaa, 0xff, 0xff},
            color.RGBA{0xff, 0xff, 0x00, 0xff},
            color.RGBA{0xff, 0xff, 0x55, 0xff},
            color.RGBA{0xff, 0xff, 0xaa, 0xff},
            color.RGBA{0xff, 0xff, 0xff, 0xff},
        }

        WebSafe is a 216-color palette that was popularized by early versions of Netscape Navigator. It is also known as the Netscape Color Cube.

        See https://en.wikipedia.org/wiki/Web_colors#Web-safe_colors for details.

        var WebSafe = []color.Color{
            color.RGBA{0x00, 0x00, 0x00, 0xff},
            color.RGBA{0x00, 0x00, 0x33, 0xff},
            color.RGBA{0x00, 0x00, 0x66, 0xff},
            color.RGBA{0x00, 0x00, 0x99, 0xff},
            color.RGBA{0x00, 0x00, 0xcc, 0xff},
            color.RGBA{0x00, 0x00, 0xff, 0xff},
            color.RGBA{0x00, 0x33, 0x00, 0xff},
            color.RGBA{0x00, 0x33, 0x33, 0xff},
            color.RGBA{0x00, 0x33, 0x66, 0xff},
            color.RGBA{0x00, 0x33, 0x99, 0xff},
            color.RGBA{0x00, 0x33, 0xcc, 0xff},
            color.RGBA{0x00, 0x33, 0xff, 0xff},
            color.RGBA{0x00, 0x66, 0x00, 0xff},
            color.RGBA{0x00, 0x66, 0x33, 0xff},
            color.RGBA{0x00, 0x66, 0x66, 0xff},
            color.RGBA{0x00, 0x66, 0x99, 0xff},
            color.RGBA{0x00, 0x66, 0xcc, 0xff},
            color.RGBA{0x00, 0x66, 0xff, 0xff},
            color.RGBA{0x00, 0x99, 0x00, 0xff},
            color.RGBA{0x00, 0x99, 0x33, 0xff},
            color.RGBA{0x00, 0x99, 0x66, 0xff},
            color.RGBA{0x00, 0x99, 0x99, 0xff},
            color.RGBA{0x00, 0x99, 0xcc, 0xff},
            color.RGBA{0x00, 0x99, 0xff, 0xff},
            color.RGBA{0x00, 0xcc, 0x00, 0xff},
            color.RGBA{0x00, 0xcc, 0x33, 0xff},
            color.RGBA{0x00, 0xcc, 0x66, 0xff},
            color.RGBA{0x00, 0xcc, 0x99, 0xff},
            color.RGBA{0x00, 0xcc, 0xcc, 0xff},
            color.RGBA{0x00, 0xcc, 0xff, 0xff},
            color.RGBA{0x00, 0xff, 0x00, 0xff},
            color.RGBA{0x00, 0xff, 0x33, 0xff},
            color.RGBA{0x00, 0xff, 0x66, 0xff},
            color.RGBA{0x00, 0xff, 0x99, 0xff},
            color.RGBA{0x00, 0xff, 0xcc, 0xff},
            color.RGBA{0x00, 0xff, 0xff, 0xff},
            color.RGBA{0x33, 0x00, 0x00, 0xff},
            color.RGBA{0x33, 0x00, 0x33, 0xff},
            color.RGBA{0x33, 0x00, 0x66, 0xff},
            color.RGBA{0x33, 0x00, 0x99, 0xff},
            color.RGBA{0x33, 0x00, 0xcc, 0xff},
            color.RGBA{0x33, 0x00, 0xff, 0xff},
            color.RGBA{0x33, 0x33, 0x00, 0xff},
            color.RGBA{0x33, 0x33, 0x33, 0xff},
            color.RGBA{0x33, 0x33, 0x66, 0xff},
            color.RGBA{0x33, 0x33, 0x99, 0xff},
            color.RGBA{0x33, 0x33, 0xcc, 0xff},
            color.RGBA{0x33, 0x33, 0xff, 0xff},
            color.RGBA{0x33, 0x66, 0x00, 0xff},
            color.RGBA{0x33, 0x66, 0x33, 0xff},
            color.RGBA{0x33, 0x66, 0x66, 0xff},
            color.RGBA{0x33, 0x66, 0x99, 0xff},
            color.RGBA{0x33, 0x66, 0xcc, 0xff},
            color.RGBA{0x33, 0x66, 0xff, 0xff},
            color.RGBA{0x33, 0x99, 0x00, 0xff},
            color.RGBA{0x33, 0x99, 0x33, 0xff},
            color.RGBA{0x33, 0x99, 0x66, 0xff},
            color.RGBA{0x33, 0x99, 0x99, 0xff},
            color.RGBA{0x33, 0x99, 0xcc, 0xff},
            color.RGBA{0x33, 0x99, 0xff, 0xff},
            color.RGBA{0x33, 0xcc, 0x00, 0xff},
            color.RGBA{0x33, 0xcc, 0x33, 0xff},
            color.RGBA{0x33, 0xcc, 0x66, 0xff},
            color.RGBA{0x33, 0xcc, 0x99, 0xff},
            color.RGBA{0x33, 0xcc, 0xcc, 0xff},
            color.RGBA{0x33, 0xcc, 0xff, 0xff},
            color.RGBA{0x33, 0xff, 0x00, 0xff},
            color.RGBA{0x33, 0xff, 0x33, 0xff},
            color.RGBA{0x33, 0xff, 0x66, 0xff},
            color.RGBA{0x33, 0xff, 0x99, 0xff},
            color.RGBA{0x33, 0xff, 0xcc, 0xff},
            color.RGBA{0x33, 0xff, 0xff, 0xff},
            color.RGBA{0x66, 0x00, 0x00, 0xff},
            color.RGBA{0x66, 0x00, 0x33, 0xff},
            color.RGBA{0x66, 0x00, 0x66, 0xff},
            color.RGBA{0x66, 0x00, 0x99, 0xff},
            color.RGBA{0x66, 0x00, 0xcc, 0xff},
            color.RGBA{0x66, 0x00, 0xff, 0xff},
            color.RGBA{0x66, 0x33, 0x00, 0xff},
            color.RGBA{0x66, 0x33, 0x33, 0xff},
            color.RGBA{0x66, 0x33, 0x66, 0xff},
            color.RGBA{0x66, 0x33, 0x99, 0xff},
            color.RGBA{0x66, 0x33, 0xcc, 0xff},
            color.RGBA{0x66, 0x33, 0xff, 0xff},
            color.RGBA{0x66, 0x66, 0x00, 0xff},
            color.RGBA{0x66, 0x66, 0x33, 0xff},
            color.RGBA{0x66, 0x66, 0x66, 0xff},
            color.RGBA{0x66, 0x66, 0x99, 0xff},
            color.RGBA{0x66, 0x66, 0xcc, 0xff},
            color.RGBA{0x66, 0x66, 0xff, 0xff},
            color.RGBA{0x66, 0x99, 0x00, 0xff},
            color.RGBA{0x66, 0x99, 0x33, 0xff},
            color.RGBA{0x66, 0x99, 0x66, 0xff},
            color.RGBA{0x66, 0x99, 0x99, 0xff},
            color.RGBA{0x66, 0x99, 0xcc, 0xff},
            color.RGBA{0x66, 0x99, 0xff, 0xff},
            color.RGBA{0x66, 0xcc, 0x00, 0xff},
            color.RGBA{0x66, 0xcc, 0x33, 0xff},
            color.RGBA{0x66, 0xcc, 0x66, 0xff},
            color.RGBA{0x66, 0xcc, 0x99, 0xff},
            color.RGBA{0x66, 0xcc, 0xcc, 0xff},
            color.RGBA{0x66, 0xcc, 0xff, 0xff},
            color.RGBA{0x66, 0xff, 0x00, 0xff},
            color.RGBA{0x66, 0xff, 0x33, 0xff},
            color.RGBA{0x66, 0xff, 0x66, 0xff},
            color.RGBA{0x66, 0xff, 0x99, 0xff},
            color.RGBA{0x66, 0xff, 0xcc, 0xff},
            color.RGBA{0x66, 0xff, 0xff, 0xff},
            color.RGBA{0x99, 0x00, 0x00, 0xff},
            color.RGBA{0x99, 0x00, 0x33, 0xff},
            color.RGBA{0x99, 0x00, 0x66, 0xff},
            color.RGBA{0x99, 0x00, 0x99, 0xff},
            color.RGBA{0x99, 0x00, 0xcc, 0xff},
            color.RGBA{0x99, 0x00, 0xff, 0xff},
            color.RGBA{0x99, 0x33, 0x00, 0xff},
            color.RGBA{0x99, 0x33, 0x33, 0xff},
            color.RGBA{0x99, 0x33, 0x66, 0xff},
            color.RGBA{0x99, 0x33, 0x99, 0xff},
            color.RGBA{0x99, 0x33, 0xcc, 0xff},
            color.RGBA{0x99, 0x33, 0xff, 0xff},
            color.RGBA{0x99, 0x66, 0x00, 0xff},
            color.RGBA{0x99, 0x66, 0x33, 0xff},
            color.RGBA{0x99, 0x66, 0x66, 0xff},
            color.RGBA{0x99, 0x66, 0x99, 0xff},
            color.RGBA{0x99, 0x66, 0xcc, 0xff},
            color.RGBA{0x99, 0x66, 0xff, 0xff},
            color.RGBA{0x99, 0x99, 0x00, 0xff},
            color.RGBA{0x99, 0x99, 0x33, 0xff},
            color.RGBA{0x99, 0x99, 0x66, 0xff},
            color.RGBA{0x99, 0x99, 0x99, 0xff},
            color.RGBA{0x99, 0x99, 0xcc, 0xff},
            color.RGBA{0x99, 0x99, 0xff, 0xff},
            color.RGBA{0x99, 0xcc, 0x00, 0xff},
            color.RGBA{0x99, 0xcc, 0x33, 0xff},
            color.RGBA{0x99, 0xcc, 0x66, 0xff},
            color.RGBA{0x99, 0xcc, 0x99, 0xff},
            color.RGBA{0x99, 0xcc, 0xcc, 0xff},
            color.RGBA{0x99, 0xcc, 0xff, 0xff},
            color.RGBA{0x99, 0xff, 0x00, 0xff},
            color.RGBA{0x99, 0xff, 0x33, 0xff},
            color.RGBA{0x99, 0xff, 0x66, 0xff},
            color.RGBA{0x99, 0xff, 0x99, 0xff},
            color.RGBA{0x99, 0xff, 0xcc, 0xff},
            color.RGBA{0x99, 0xff, 0xff, 0xff},
            color.RGBA{0xcc, 0x00, 0x00, 0xff},
            color.RGBA{0xcc, 0x00, 0x33, 0xff},
            color.RGBA{0xcc, 0x00, 0x66, 0xff},
            color.RGBA{0xcc, 0x00, 0x99, 0xff},
            color.RGBA{0xcc, 0x00, 0xcc, 0xff},
            color.RGBA{0xcc, 0x00, 0xff, 0xff},
            color.RGBA{0xcc, 0x33, 0x00, 0xff},
            color.RGBA{0xcc, 0x33, 0x33, 0xff},
            color.RGBA{0xcc, 0x33, 0x66, 0xff},
            color.RGBA{0xcc, 0x33, 0x99, 0xff},
            color.RGBA{0xcc, 0x33, 0xcc, 0xff},
            color.RGBA{0xcc, 0x33, 0xff, 0xff},
            color.RGBA{0xcc, 0x66, 0x00, 0xff},
            color.RGBA{0xcc, 0x66, 0x33, 0xff},
            color.RGBA{0xcc, 0x66, 0x66, 0xff},
            color.RGBA{0xcc, 0x66, 0x99, 0xff},
            color.RGBA{0xcc, 0x66, 0xcc, 0xff},
            color.RGBA{0xcc, 0x66, 0xff, 0xff},
            color.RGBA{0xcc, 0x99, 0x00, 0xff},
            color.RGBA{0xcc, 0x99, 0x33, 0xff},
            color.RGBA{0xcc, 0x99, 0x66, 0xff},
            color.RGBA{0xcc, 0x99, 0x99, 0xff},
            color.RGBA{0xcc, 0x99, 0xcc, 0xff},
            color.RGBA{0xcc, 0x99, 0xff, 0xff},
            color.RGBA{0xcc, 0xcc, 0x00, 0xff},
            color.RGBA{0xcc, 0xcc, 0x33, 0xff},
            color.RGBA{0xcc, 0xcc, 0x66, 0xff},
            color.RGBA{0xcc, 0xcc, 0x99, 0xff},
            color.RGBA{0xcc, 0xcc, 0xcc, 0xff},
            color.RGBA{0xcc, 0xcc, 0xff, 0xff},
            color.RGBA{0xcc, 0xff, 0x00, 0xff},
            color.RGBA{0xcc, 0xff, 0x33, 0xff},
            color.RGBA{0xcc, 0xff, 0x66, 0xff},
            color.RGBA{0xcc, 0xff, 0x99, 0xff},
            color.RGBA{0xcc, 0xff, 0xcc, 0xff},
            color.RGBA{0xcc, 0xff, 0xff, 0xff},
            color.RGBA{0xff, 0x00, 0x00, 0xff},
            color.RGBA{0xff, 0x00, 0x33, 0xff},
            color.RGBA{0xff, 0x00, 0x66, 0xff},
            color.RGBA{0xff, 0x00, 0x99, 0xff},
            color.RGBA{0xff, 0x00, 0xcc, 0xff},
            color.RGBA{0xff, 0x00, 0xff, 0xff},
            color.RGBA{0xff, 0x33, 0x00, 0xff},
            color.RGBA{0xff, 0x33, 0x33, 0xff},
            color.RGBA{0xff, 0x33, 0x66, 0xff},
            color.RGBA{0xff, 0x33, 0x99, 0xff},
            color.RGBA{0xff, 0x33, 0xcc, 0xff},
            color.RGBA{0xff, 0x33, 0xff, 0xff},
            color.RGBA{0xff, 0x66, 0x00, 0xff},
            color.RGBA{0xff, 0x66, 0x33, 0xff},
            color.RGBA{0xff, 0x66, 0x66, 0xff},
            color.RGBA{0xff, 0x66, 0x99, 0xff},
            color.RGBA{0xff, 0x66, 0xcc, 0xff},
            color.RGBA{0xff, 0x66, 0xff, 0xff},
            color.RGBA{0xff, 0x99, 0x00, 0xff},
            color.RGBA{0xff, 0x99, 0x33, 0xff},
            color.RGBA{0xff, 0x99, 0x66, 0xff},
            color.RGBA{0xff, 0x99, 0x99, 0xff},
            color.RGBA{0xff, 0x99, 0xcc, 0xff},
            color.RGBA{0xff, 0x99, 0xff, 0xff},
            color.RGBA{0xff, 0xcc, 0x00, 0xff},
            color.RGBA{0xff, 0xcc, 0x33, 0xff},
            color.RGBA{0xff, 0xcc, 0x66, 0xff},
            color.RGBA{0xff, 0xcc, 0x99, 0xff},
            color.RGBA{0xff, 0xcc, 0xcc, 0xff},
            color.RGBA{0xff, 0xcc, 0xff, 0xff},
            color.RGBA{0xff, 0xff, 0x00, 0xff},
            color.RGBA{0xff, 0xff, 0x33, 0xff},
            color.RGBA{0xff, 0xff, 0x66, 0xff},
            color.RGBA{0xff, 0xff, 0x99, 0xff},
            color.RGBA{0xff, 0xff, 0xcc, 0xff},
            color.RGBA{0xff, 0xff, 0xff, 0xff},
        }
        draw - Go Documentation Server
        ...

        Package draw

        import "image/draw"
        Overview
        Index
        Examples

        Overview ▾

        Package draw provides image composition functions.

        See "The Go image/draw package" for an introduction to this package: https://golang.org/doc/articles/image_draw.html

        func Draw

        func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op)

        Draw calls DrawMask with a nil mask.

        func DrawMask

        func DrawMask(dst Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point, op Op)

        DrawMask aligns r.Min in dst with sp in src and mp in mask and then replaces the rectangle r in dst with the result of a Porter-Duff composition. A nil mask is treated as opaque.

        type Drawer

        Drawer contains the Draw method.

        type Drawer interface {
            // Draw aligns r.Min in dst with sp in src and then replaces the
            // rectangle r in dst with the result of drawing src on dst.
            Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point)
        }

        FloydSteinberg is a Drawer that is the Src Op with Floyd-Steinberg error diffusion.

        var FloydSteinberg Drawer = floydSteinberg{}

        Example (FloydSteinberg)

        Code:

        const width = 130
        const height = 50
        
        im := image.NewGray(image.Rectangle{Max: image.Point{X: width, Y: height}})
        for x := 0; x < width; x++ {
            for y := 0; y < height; y++ {
                dist := math.Sqrt(math.Pow(float64(x-width/2), 2)/3+math.Pow(float64(y-height/2), 2)) / (height / 1.5) * 255
                var gray uint8
                if dist > 255 {
                    gray = 255
                } else {
                    gray = uint8(dist)
                }
                im.SetGray(x, y, color.Gray{Y: 255 - gray})
            }
        }
        pi := image.NewPaletted(im.Bounds(), []color.Color{
            color.Gray{Y: 255},
            color.Gray{Y: 160},
            color.Gray{Y: 70},
            color.Gray{Y: 35},
            color.Gray{Y: 0},
        })
        
        draw.FloydSteinberg.Draw(pi, im.Bounds(), im, image.Point{})
        shade := []string{" ", "░", "▒", "▓", "█"}
        for i, p := range pi.Pix {
            fmt.Print(shade[p])
            if (i+1)%width == 0 {
                fmt.Print("\n")
            }
        }
        

        type Image

        Image is an image.Image with a Set method to change a single pixel.

        type Image interface {
            image.Image
            Set(x, y int, c color.Color)
        }

        type Op

        Op is a Porter-Duff compositing operator.

        type Op int
        const (
            // Over specifies ``(src in mask) over dst''.
            Over Op = iota
            // Src specifies ``src in mask''.
            Src
        )

        func (Op) Draw

        func (op Op) Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point)

        Draw implements the Drawer interface by calling the Draw function with this Op.

        type Quantizer

        Quantizer produces a palette for an image.

        type Quantizer interface {
            // Quantize appends up to cap(p) - len(p) colors to p and returns the
            // updated palette suitable for converting m to a paletted image.
            Quantize(p color.Palette, m image.Image) color.Palette
        }

        type RGBA64Image

        RGBA64Image extends both the Image and image.RGBA64Image interfaces with a SetRGBA64 method to change a single pixel. SetRGBA64 is equivalent to calling Set, but it can avoid allocations from converting concrete color types to the color.Color interface type.

        type RGBA64Image interface {
            image.RGBA64Image
            Set(x, y int, c color.Color)
            SetRGBA64(x, y int, c color.RGBA64)
        }
        gif - Go Documentation Server
        ...

        Package gif

        import "image/gif"
        Overview
        Index

        Overview ▾

        Package gif implements a GIF image decoder and encoder.

        The GIF specification is at https://www.w3.org/Graphics/GIF/spec-gif89a.txt.

        Constants

        Disposal Methods.

        const (
            DisposalNone       = 0x01
            DisposalBackground = 0x02
            DisposalPrevious   = 0x03
        )

        func Decode

        func Decode(r io.Reader) (image.Image, error)

        Decode reads a GIF image from r and returns the first embedded image as an image.Image.

        func DecodeConfig

        func DecodeConfig(r io.Reader) (image.Config, error)

        DecodeConfig returns the global color model and dimensions of a GIF image without decoding the entire image.

        func Encode

        func Encode(w io.Writer, m image.Image, o *Options) error

        Encode writes the Image m to w in GIF format.

        func EncodeAll

        func EncodeAll(w io.Writer, g *GIF) error

        EncodeAll writes the images in g to w in GIF format with the given loop count and delay between frames.

        type GIF

        GIF represents the possibly multiple images stored in a GIF file.

        type GIF struct {
            Image []*image.Paletted // The successive images.
            Delay []int             // The successive delay times, one per frame, in 100ths of a second.
            // LoopCount controls the number of times an animation will be
            // restarted during display.
            // A LoopCount of 0 means to loop forever.
            // A LoopCount of -1 means to show each frame only once.
            // Otherwise, the animation is looped LoopCount+1 times.
            LoopCount int
            // Disposal is the successive disposal methods, one per frame. For
            // backwards compatibility, a nil Disposal is valid to pass to EncodeAll,
            // and implies that each frame's disposal method is 0 (no disposal
            // specified).
            Disposal []byte
            // Config is the global color table (palette), width and height. A nil or
            // empty-color.Palette Config.ColorModel means that each frame has its own
            // color table and there is no global color table. Each frame's bounds must
            // be within the rectangle defined by the two points (0, 0) and
            // (Config.Width, Config.Height).
            //
            // For backwards compatibility, a zero-valued Config is valid to pass to
            // EncodeAll, and implies that the overall GIF's width and height equals
            // the first frame's bounds' Rectangle.Max point.
            Config image.Config
            // BackgroundIndex is the background index in the global color table, for
            // use with the DisposalBackground disposal method.
            BackgroundIndex byte
        }
        

        func DecodeAll

        func DecodeAll(r io.Reader) (*GIF, error)

        DecodeAll reads a GIF image from r and returns the sequential frames and timing information.

        type Options

        Options are the encoding parameters.

        type Options struct {
            // NumColors is the maximum number of colors used in the image.
            // It ranges from 1 to 256.
            NumColors int
        
            // Quantizer is used to produce a palette with size NumColors.
            // palette.Plan9 is used in place of a nil Quantizer.
            Quantizer draw.Quantizer
        
            // Drawer is used to convert the source image to the desired palette.
            // draw.FloydSteinberg is used in place of a nil Drawer.
            Drawer draw.Drawer
        }
        
        jpeg - Go Documentation Server
        ...

        Package jpeg

        import "image/jpeg"
        Overview
        Index

        Overview ▾

        Package jpeg implements a JPEG image decoder and encoder.

        JPEG is defined in ITU-T T.81: https://www.w3.org/Graphics/JPEG/itu-t81.pdf.

        Constants

        DefaultQuality is the default quality encoding parameter.

        const DefaultQuality = 75

        func Decode

        func Decode(r io.Reader) (image.Image, error)

        Decode reads a JPEG image from r and returns it as an image.Image.

        func DecodeConfig

        func DecodeConfig(r io.Reader) (image.Config, error)

        DecodeConfig returns the color model and dimensions of a JPEG image without decoding the entire image.

        func Encode

        func Encode(w io.Writer, m image.Image, o *Options) error

        Encode writes the Image m to w in JPEG 4:2:0 baseline format with the given options. Default parameters are used if a nil *Options is passed.

        type FormatError

        A FormatError reports that the input is not a valid JPEG.

        type FormatError string

        func (FormatError) Error

        func (e FormatError) Error() string

        type Options

        Options are the encoding parameters. Quality ranges from 1 to 100 inclusive, higher is better.

        type Options struct {
            Quality int
        }
        

        type Reader

        Deprecated: Reader is not used by the image/jpeg package and should not be used by others. It is kept for compatibility.

        type Reader interface {
            io.ByteReader
            io.Reader
        }

        type UnsupportedError

        An UnsupportedError reports that the input uses a valid but unimplemented JPEG feature.

        type UnsupportedError string

        func (UnsupportedError) Error

        func (e UnsupportedError) Error() string
        png - Go Documentation Server
        ...

        Package png

        import "image/png"
        Overview
        Index
        Examples

        Overview ▾

        Package png implements a PNG image decoder and encoder.

        The PNG specification is at https://www.w3.org/TR/PNG/.

        func Decode

        func Decode(r io.Reader) (image.Image, error)

        Decode reads a PNG image from r and returns it as an image.Image. The type of Image returned depends on the PNG contents.

        Example

        Code:

        // This example uses png.Decode which can only decode PNG images.
        // Consider using the general image.Decode as it can sniff and decode any registered image format.
        img, err := png.Decode(gopherPNG())
        if err != nil {
            log.Fatal(err)
        }
        
        levels := []string{" ", "░", "▒", "▓", "█"}
        
        for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
            for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
                c := color.GrayModel.Convert(img.At(x, y)).(color.Gray)
                level := c.Y / 51 // 51 * 5 = 255
                if level == 5 {
                    level--
                }
                fmt.Print(levels[level])
            }
            fmt.Print("\n")
        }
        

        func DecodeConfig

        func DecodeConfig(r io.Reader) (image.Config, error)

        DecodeConfig returns the color model and dimensions of a PNG image without decoding the entire image.

        func Encode

        func Encode(w io.Writer, m image.Image) error

        Encode writes the Image m to w in PNG format. Any Image may be encoded, but images that are not image.NRGBA might be encoded lossily.

        Example

        Code:

        const width, height = 256, 256
        
        // Create a colored image of the given width and height.
        img := image.NewNRGBA(image.Rect(0, 0, width, height))
        
        for y := 0; y < height; y++ {
            for x := 0; x < width; x++ {
                img.Set(x, y, color.NRGBA{
                    R: uint8((x + y) & 255),
                    G: uint8((x + y) << 1 & 255),
                    B: uint8((x + y) << 2 & 255),
                    A: 255,
                })
            }
        }
        
        f, err := os.Create("image.png")
        if err != nil {
            log.Fatal(err)
        }
        
        if err := png.Encode(f, img); err != nil {
            f.Close()
            log.Fatal(err)
        }
        
        if err := f.Close(); err != nil {
            log.Fatal(err)
        }
        

        type CompressionLevel

        CompressionLevel indicates the compression level.

        type CompressionLevel int
        const (
            DefaultCompression CompressionLevel = 0
            NoCompression      CompressionLevel = -1
            BestSpeed          CompressionLevel = -2
            BestCompression    CompressionLevel = -3
        )

        type Encoder

        Encoder configures encoding PNG images.

        type Encoder struct {
            CompressionLevel CompressionLevel
        
            // BufferPool optionally specifies a buffer pool to get temporary
            // EncoderBuffers when encoding an image.
            BufferPool EncoderBufferPool
        }
        

        func (*Encoder) Encode

        func (enc *Encoder) Encode(w io.Writer, m image.Image) error

        Encode writes the Image m to w in PNG format.

        type EncoderBuffer

        EncoderBuffer holds the buffers used for encoding PNG images.

        type EncoderBuffer encoder

        type EncoderBufferPool

        EncoderBufferPool is an interface for getting and returning temporary instances of the EncoderBuffer struct. This can be used to reuse buffers when encoding multiple images.

        type EncoderBufferPool interface {
            Get() *EncoderBuffer
            Put(*EncoderBuffer)
        }

        type FormatError

        A FormatError reports that the input is not a valid PNG.

        type FormatError string

        func (FormatError) Error

        func (e FormatError) Error() string

        type UnsupportedError

        An UnsupportedError reports that the input uses a valid but unimplemented PNG feature.

        type UnsupportedError string

        func (UnsupportedError) Error

        func (e UnsupportedError) Error() string
        /src/index - Go Documentation Server
        ...

        Directory /src/index

        Name Synopsis
        ..
        suffixarray Package suffixarray implements substring search in logarithmic time using an in-memory suffix array.
        suffixarray - Go Documentation Server
        ...

        Package suffixarray

        import "index/suffixarray"
        Overview
        Index
        Examples

        Overview ▾

        Package suffixarray implements substring search in logarithmic time using an in-memory suffix array.

        Example use:

        // create index for some data
        index := suffixarray.New(data)
        
        // lookup byte slice s
        offsets1 := index.Lookup(s, -1) // the list of all indices where s occurs in data
        offsets2 := index.Lookup(s, 3)  // the list of at most 3 indices where s occurs in data
        

        type Index

        Index implements a suffix array for fast substring search.

        type Index struct {
            // contains filtered or unexported fields
        }
        

        func New

        func New(data []byte) *Index

        New creates a new Index for data. Index creation time is O(N) for N = len(data).

        func (*Index) Bytes

        func (x *Index) Bytes() []byte

        Bytes returns the data over which the index was created. It must not be modified.

        func (*Index) FindAllIndex

        func (x *Index) FindAllIndex(r *regexp.Regexp, n int) (result [][]int)

        FindAllIndex returns a sorted list of non-overlapping matches of the regular expression r, where a match is a pair of indices specifying the matched slice of x.Bytes(). If n < 0, all matches are returned in successive order. Otherwise, at most n matches are returned and they may not be successive. The result is nil if there are no matches, or if n == 0.

        func (*Index) Lookup

        func (x *Index) Lookup(s []byte, n int) (result []int)

        Lookup returns an unsorted list of at most n indices where the byte string s occurs in the indexed data. If n < 0, all occurrences are returned. The result is nil if s is empty, s is not found, or n == 0. Lookup time is O(log(N)*len(s) + len(result)) where N is the size of the indexed data.

        Example

        Code:

        index := suffixarray.New([]byte("banana"))
        offsets := index.Lookup([]byte("ana"), -1)
        for _, off := range offsets {
            fmt.Println(off)
        }
        
        

        Output:

        1
        3
        

        func (*Index) Read

        func (x *Index) Read(r io.Reader) error

        Read reads the index from r into x; x must not be nil.

        func (*Index) Write

        func (x *Index) Write(w io.Writer) error

        Write writes the index x to w.

        io - Go Documentation Server
        ...

        Package io

        Overview ▾

        Package io provides basic interfaces to I/O primitives. Its primary job is to wrap existing implementations of such primitives, such as those in package os, into shared public interfaces that abstract the functionality, plus some other related primitives.

        Because these interfaces and primitives wrap lower-level operations with various implementations, unless otherwise informed clients should not assume they are safe for parallel execution.

        Index ▾

        Constants
        Variables
        func Copy(dst Writer, src Reader) (written int64, err error)
        func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)
        func CopyN(dst Writer, src Reader, n int64) (written int64, err error)
        func Pipe() (*PipeReader, *PipeWriter)
        func ReadAll(r Reader) ([]byte, error)
        func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error)
        func ReadFull(r Reader, buf []byte) (n int, err error)
        func WriteString(w Writer, s string) (n int, err error)
        type ByteReader
        type ByteScanner
        type ByteWriter
        type Closer
        type LimitedReader
            func (l *LimitedReader) Read(p []byte) (n int, err error)
        type OffsetWriter
            func NewOffsetWriter(w WriterAt, off int64) *OffsetWriter
            func (o *OffsetWriter) Seek(offset int64, whence int) (int64, error)
            func (o *OffsetWriter) Write(p []byte) (n int, err error)
            func (o *OffsetWriter) WriteAt(p []byte, off int64) (n int, err error)
        type PipeReader
            func (r *PipeReader) Close() error
            func (r *PipeReader) CloseWithError(err error) error
            func (r *PipeReader) Read(data []byte) (n int, err error)
        type PipeWriter
            func (w *PipeWriter) Close() error
            func (w *PipeWriter) CloseWithError(err error) error
            func (w *PipeWriter) Write(data []byte) (n int, err error)
        type ReadCloser
            func NopCloser(r Reader) ReadCloser
        type ReadSeekCloser
        type ReadSeeker
        type ReadWriteCloser
        type ReadWriteSeeker
        type ReadWriter
        type Reader
            func LimitReader(r Reader, n int64) Reader
            func MultiReader(readers ...Reader) Reader
            func TeeReader(r Reader, w Writer) Reader
        type ReaderAt
        type ReaderFrom
        type RuneReader
        type RuneScanner
        type SectionReader
            func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader
            func (s *SectionReader) Outer() (r ReaderAt, off int64, n int64)
            func (s *SectionReader) Read(p []byte) (n int, err error)
            func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error)
            func (s *SectionReader) Seek(offset int64, whence int) (int64, error)
            func (s *SectionReader) Size() int64
        type Seeker
        type StringWriter
        type WriteCloser
        type WriteSeeker
        type Writer
            func MultiWriter(writers ...Writer) Writer
        type WriterAt
        type WriterTo

        Package files

        io.go multi.go pipe.go

        Constants

        Seek whence values.

        const (
            SeekStart   = 0 // seek relative to the origin of the file
            SeekCurrent = 1 // seek relative to the current offset
            SeekEnd     = 2 // seek relative to the end
        )

        Variables

        EOF is the error returned by Read when no more input is available. (Read must return EOF itself, not an error wrapping EOF, because callers will test for EOF using ==.) Functions should return EOF only to signal a graceful end of input. If the EOF occurs unexpectedly in a structured data stream, the appropriate error is either ErrUnexpectedEOF or some other error giving more detail.

        var EOF = errors.New("EOF")

        ErrClosedPipe is the error used for read or write operations on a closed pipe.

        var ErrClosedPipe = errors.New("io: read/write on closed pipe")

        ErrNoProgress is returned by some clients of a Reader when many calls to Read have failed to return any data or error, usually the sign of a broken Reader implementation.

        var ErrNoProgress = errors.New("multiple Read calls return no data or error")

        ErrShortBuffer means that a read required a longer buffer than was provided.

        var ErrShortBuffer = errors.New("short buffer")

        ErrShortWrite means that a write accepted fewer bytes than requested but failed to return an explicit error.

        var ErrShortWrite = errors.New("short write")

        ErrUnexpectedEOF means that EOF was encountered in the middle of reading a fixed-size block or data structure.

        var ErrUnexpectedEOF = errors.New("unexpected EOF")

        func Copy

        func Copy(dst Writer, src Reader) (written int64, err error)

        Copy copies from src to dst until either EOF is reached on src or an error occurs. It returns the number of bytes copied and the first error encountered while copying, if any.

        A successful Copy returns err == nil, not err == EOF. Because Copy is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.

        If src implements WriterTo, the copy is implemented by calling src.WriteTo(dst). Otherwise, if dst implements ReaderFrom, the copy is implemented by calling dst.ReadFrom(src).

        Example

        Code:

        r := strings.NewReader("some io.Reader stream to be read\n")
        
        if _, err := io.Copy(os.Stdout, r); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        some io.Reader stream to be read
        

        func CopyBuffer

        func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)

        CopyBuffer is identical to Copy except that it stages through the provided buffer (if one is required) rather than allocating a temporary one. If buf is nil, one is allocated; otherwise if it has zero length, CopyBuffer panics.

        If either src implements WriterTo or dst implements ReaderFrom, buf will not be used to perform the copy.

        Example

        Code:

        r1 := strings.NewReader("first reader\n")
        r2 := strings.NewReader("second reader\n")
        buf := make([]byte, 8)
        
        // buf is used here...
        if _, err := io.CopyBuffer(os.Stdout, r1, buf); err != nil {
            log.Fatal(err)
        }
        
        // ... reused here also. No need to allocate an extra buffer.
        if _, err := io.CopyBuffer(os.Stdout, r2, buf); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        first reader
        second reader
        

        func CopyN

        func CopyN(dst Writer, src Reader, n int64) (written int64, err error)

        CopyN copies n bytes (or until an error) from src to dst. It returns the number of bytes copied and the earliest error encountered while copying. On return, written == n if and only if err == nil.

        If dst implements ReaderFrom, the copy is implemented using it.

        Example

        Code:

        r := strings.NewReader("some io.Reader stream to be read")
        
        if _, err := io.CopyN(os.Stdout, r, 4); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        some
        

        func Pipe

        func Pipe() (*PipeReader, *PipeWriter)

        Pipe creates a synchronous in-memory pipe. It can be used to connect code expecting an io.Reader with code expecting an io.Writer.

        Reads and Writes on the pipe are matched one to one except when multiple Reads are needed to consume a single Write. That is, each Write to the PipeWriter blocks until it has satisfied one or more Reads from the PipeReader that fully consume the written data. The data is copied directly from the Write to the corresponding Read (or Reads); there is no internal buffering.

        It is safe to call Read and Write in parallel with each other or with Close. Parallel calls to Read and parallel calls to Write are also safe: the individual calls will be gated sequentially.

        Example

        Code:

        r, w := io.Pipe()
        
        go func() {
            fmt.Fprint(w, "some io.Reader stream to be read\n")
            w.Close()
        }()
        
        if _, err := io.Copy(os.Stdout, r); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        some io.Reader stream to be read
        

        func ReadAll

        func ReadAll(r Reader) ([]byte, error)

        ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.

        Example

        Code:

        r := strings.NewReader("Go is a general-purpose language designed with systems programming in mind.")
        
        b, err := io.ReadAll(r)
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%s", b)
        
        

        Output:

        Go is a general-purpose language designed with systems programming in mind.
        

        func ReadAtLeast

        func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error)

        ReadAtLeast reads from r into buf until it has read at least min bytes. It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read. If an EOF happens after reading fewer than min bytes, ReadAtLeast returns ErrUnexpectedEOF. If min is greater than the length of buf, ReadAtLeast returns ErrShortBuffer. On return, n >= min if and only if err == nil. If r returns an error having read at least min bytes, the error is dropped.

        Example

        Code:

        r := strings.NewReader("some io.Reader stream to be read\n")
        
        buf := make([]byte, 14)
        if _, err := io.ReadAtLeast(r, buf, 4); err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s\n", buf)
        
        // buffer smaller than minimal read size.
        shortBuf := make([]byte, 3)
        if _, err := io.ReadAtLeast(r, shortBuf, 4); err != nil {
            fmt.Println("error:", err)
        }
        
        // minimal read size bigger than io.Reader stream
        longBuf := make([]byte, 64)
        if _, err := io.ReadAtLeast(r, longBuf, 64); err != nil {
            fmt.Println("error:", err)
        }
        
        

        Output:

        some io.Reader
        error: short buffer
        error: unexpected EOF
        

        func ReadFull

        func ReadFull(r Reader, buf []byte) (n int, err error)

        ReadFull reads exactly len(buf) bytes from r into buf. It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadFull returns ErrUnexpectedEOF. On return, n == len(buf) if and only if err == nil. If r returns an error having read at least len(buf) bytes, the error is dropped.

        Example

        Code:

        r := strings.NewReader("some io.Reader stream to be read\n")
        
        buf := make([]byte, 4)
        if _, err := io.ReadFull(r, buf); err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s\n", buf)
        
        // minimal read size bigger than io.Reader stream
        longBuf := make([]byte, 64)
        if _, err := io.ReadFull(r, longBuf); err != nil {
            fmt.Println("error:", err)
        }
        
        

        Output:

        some
        error: unexpected EOF
        

        func WriteString

        func WriteString(w Writer, s string) (n int, err error)

        WriteString writes the contents of the string s to w, which accepts a slice of bytes. If w implements StringWriter, [StringWriter.WriteString] is invoked directly. Otherwise, [Writer.Write] is called exactly once.

        Example

        Code:

        if _, err := io.WriteString(os.Stdout, "Hello World"); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        Hello World
        

        type ByteReader

        ByteReader is the interface that wraps the ReadByte method.

        ReadByte reads and returns the next byte from the input or any error encountered. If ReadByte returns an error, no input byte was consumed, and the returned byte value is undefined.

        ReadByte provides an efficient interface for byte-at-time processing. A Reader that does not implement ByteReader can be wrapped using bufio.NewReader to add this method.

        type ByteReader interface {
            ReadByte() (byte, error)
        }

        type ByteScanner

        ByteScanner is the interface that adds the UnreadByte method to the basic ReadByte method.

        UnreadByte causes the next call to ReadByte to return the last byte read. If the last operation was not a successful call to ReadByte, UnreadByte may return an error, unread the last byte read (or the byte prior to the last-unread byte), or (in implementations that support the Seeker interface) seek to one byte before the current offset.

        type ByteScanner interface {
            ByteReader
            UnreadByte() error
        }

        type ByteWriter

        ByteWriter is the interface that wraps the WriteByte method.

        type ByteWriter interface {
            WriteByte(c byte) error
        }

        type Closer

        Closer is the interface that wraps the basic Close method.

        The behavior of Close after the first call is undefined. Specific implementations may document their own behavior.

        type Closer interface {
            Close() error
        }

        type LimitedReader

        A LimitedReader reads from R but limits the amount of data returned to just N bytes. Each call to Read updates N to reflect the new amount remaining. Read returns EOF when N <= 0 or when the underlying R returns EOF.

        type LimitedReader struct {
            R Reader // underlying reader
            N int64  // max bytes remaining
        }
        

        func (*LimitedReader) Read

        func (l *LimitedReader) Read(p []byte) (n int, err error)

        type OffsetWriter

        An OffsetWriter maps writes at offset base to offset base+off in the underlying writer.

        type OffsetWriter struct {
            // contains filtered or unexported fields
        }
        

        func NewOffsetWriter

        func NewOffsetWriter(w WriterAt, off int64) *OffsetWriter

        NewOffsetWriter returns an OffsetWriter that writes to w starting at offset off.

        func (*OffsetWriter) Seek

        func (o *OffsetWriter) Seek(offset int64, whence int) (int64, error)

        func (*OffsetWriter) Write

        func (o *OffsetWriter) Write(p []byte) (n int, err error)

        func (*OffsetWriter) WriteAt

        func (o *OffsetWriter) WriteAt(p []byte, off int64) (n int, err error)

        type PipeReader

        A PipeReader is the read half of a pipe.

        type PipeReader struct {
            // contains filtered or unexported fields
        }
        

        func (*PipeReader) Close

        func (r *PipeReader) Close() error

        Close closes the reader; subsequent writes to the write half of the pipe will return the error ErrClosedPipe.

        func (*PipeReader) CloseWithError

        func (r *PipeReader) CloseWithError(err error) error

        CloseWithError closes the reader; subsequent writes to the write half of the pipe will return the error err.

        CloseWithError never overwrites the previous error if it exists and always returns nil.

        func (*PipeReader) Read

        func (r *PipeReader) Read(data []byte) (n int, err error)

        Read implements the standard Read interface: it reads data from the pipe, blocking until a writer arrives or the write end is closed. If the write end is closed with an error, that error is returned as err; otherwise err is EOF.

        type PipeWriter

        A PipeWriter is the write half of a pipe.

        type PipeWriter struct {
            // contains filtered or unexported fields
        }
        

        func (*PipeWriter) Close

        func (w *PipeWriter) Close() error

        Close closes the writer; subsequent reads from the read half of the pipe will return no bytes and EOF.

        func (*PipeWriter) CloseWithError

        func (w *PipeWriter) CloseWithError(err error) error

        CloseWithError closes the writer; subsequent reads from the read half of the pipe will return no bytes and the error err, or EOF if err is nil.

        CloseWithError never overwrites the previous error if it exists and always returns nil.

        func (*PipeWriter) Write

        func (w *PipeWriter) Write(data []byte) (n int, err error)

        Write implements the standard Write interface: it writes data to the pipe, blocking until one or more readers have consumed all the data or the read end is closed. If the read end is closed with an error, that err is returned as err; otherwise err is ErrClosedPipe.

        type ReadCloser

        ReadCloser is the interface that groups the basic Read and Close methods.

        type ReadCloser interface {
            Reader
            Closer
        }

        func NopCloser

        func NopCloser(r Reader) ReadCloser

        NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r. If r implements WriterTo, the returned ReadCloser will implement WriterTo by forwarding calls to r.

        type ReadSeekCloser

        ReadSeekCloser is the interface that groups the basic Read, Seek and Close methods.

        type ReadSeekCloser interface {
            Reader
            Seeker
            Closer
        }

        type ReadSeeker

        ReadSeeker is the interface that groups the basic Read and Seek methods.

        type ReadSeeker interface {
            Reader
            Seeker
        }

        type ReadWriteCloser

        ReadWriteCloser is the interface that groups the basic Read, Write and Close methods.

        type ReadWriteCloser interface {
            Reader
            Writer
            Closer
        }

        type ReadWriteSeeker

        ReadWriteSeeker is the interface that groups the basic Read, Write and Seek methods.

        type ReadWriteSeeker interface {
            Reader
            Writer
            Seeker
        }

        type ReadWriter

        ReadWriter is the interface that groups the basic Read and Write methods.

        type ReadWriter interface {
            Reader
            Writer
        }

        type Reader

        Reader is the interface that wraps the basic Read method.

        Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.

        When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == EOF or err == nil. The next Read should return 0, EOF.

        Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed EOF behaviors.

        If len(p) == 0, Read should always return n == 0. It may return a non-nil error if some error condition is known, such as EOF.

        Implementations of Read are discouraged from returning a zero byte count with a nil error, except when len(p) == 0. Callers should treat a return of 0 and nil as indicating that nothing happened; in particular it does not indicate EOF.

        Implementations must not retain p.

        type Reader interface {
            Read(p []byte) (n int, err error)
        }

        func LimitReader

        func LimitReader(r Reader, n int64) Reader

        LimitReader returns a Reader that reads from r but stops with EOF after n bytes. The underlying implementation is a *LimitedReader.

        Example

        Code:

        r := strings.NewReader("some io.Reader stream to be read\n")
        lr := io.LimitReader(r, 4)
        
        if _, err := io.Copy(os.Stdout, lr); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        some
        

        func MultiReader

        func MultiReader(readers ...Reader) Reader

        MultiReader returns a Reader that's the logical concatenation of the provided input readers. They're read sequentially. Once all inputs have returned EOF, Read will return EOF. If any of the readers return a non-nil, non-EOF error, Read will return that error.

        Example

        Code:

        r1 := strings.NewReader("first reader ")
        r2 := strings.NewReader("second reader ")
        r3 := strings.NewReader("third reader\n")
        r := io.MultiReader(r1, r2, r3)
        
        if _, err := io.Copy(os.Stdout, r); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        first reader second reader third reader
        

        func TeeReader

        func TeeReader(r Reader, w Writer) Reader

        TeeReader returns a Reader that writes to w what it reads from r. All reads from r performed through it are matched with corresponding writes to w. There is no internal buffering - the write must complete before the read completes. Any error encountered while writing is reported as a read error.

        Example

        Code:

        var r io.Reader = strings.NewReader("some io.Reader stream to be read\n")
        
        r = io.TeeReader(r, os.Stdout)
        
        // Everything read from r will be copied to stdout.
        if _, err := io.ReadAll(r); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        some io.Reader stream to be read
        

        type ReaderAt

        ReaderAt is the interface that wraps the basic ReadAt method.

        ReadAt reads len(p) bytes into p starting at offset off in the underlying input source. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered.

        When ReadAt returns n < len(p), it returns a non-nil error explaining why more bytes were not returned. In this respect, ReadAt is stricter than Read.

        Even if ReadAt returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, ReadAt blocks until either all the data is available or an error occurs. In this respect ReadAt is different from Read.

        If the n = len(p) bytes returned by ReadAt are at the end of the input source, ReadAt may return either err == EOF or err == nil.

        If ReadAt is reading from an input source with a seek offset, ReadAt should not affect nor be affected by the underlying seek offset.

        Clients of ReadAt can execute parallel ReadAt calls on the same input source.

        Implementations must not retain p.

        type ReaderAt interface {
            ReadAt(p []byte, off int64) (n int, err error)
        }

        type ReaderFrom

        ReaderFrom is the interface that wraps the ReadFrom method.

        ReadFrom reads data from r until EOF or error. The return value n is the number of bytes read. Any error except EOF encountered during the read is also returned.

        The Copy function uses ReaderFrom if available.

        type ReaderFrom interface {
            ReadFrom(r Reader) (n int64, err error)
        }

        type RuneReader

        RuneReader is the interface that wraps the ReadRune method.

        ReadRune reads a single encoded Unicode character and returns the rune and its size in bytes. If no character is available, err will be set.

        type RuneReader interface {
            ReadRune() (r rune, size int, err error)
        }

        type RuneScanner

        RuneScanner is the interface that adds the UnreadRune method to the basic ReadRune method.

        UnreadRune causes the next call to ReadRune to return the last rune read. If the last operation was not a successful call to ReadRune, UnreadRune may return an error, unread the last rune read (or the rune prior to the last-unread rune), or (in implementations that support the Seeker interface) seek to the start of the rune before the current offset.

        type RuneScanner interface {
            RuneReader
            UnreadRune() error
        }

        type SectionReader

        SectionReader implements Read, Seek, and ReadAt on a section of an underlying ReaderAt.

        type SectionReader struct {
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        r := strings.NewReader("some io.Reader stream to be read\n")
        s := io.NewSectionReader(r, 5, 17)
        
        if _, err := io.Copy(os.Stdout, s); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        io.Reader stream
        

        func NewSectionReader

        func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader

        NewSectionReader returns a SectionReader that reads from r starting at offset off and stops with EOF after n bytes.

        func (*SectionReader) Outer

        func (s *SectionReader) Outer() (r ReaderAt, off int64, n int64)

        Outer returns the underlying ReaderAt and offsets for the section.

        The returned values are the same that were passed to NewSectionReader when the SectionReader was created.

        func (*SectionReader) Read

        func (s *SectionReader) Read(p []byte) (n int, err error)

        Example

        Code:

        r := strings.NewReader("some io.Reader stream to be read\n")
        s := io.NewSectionReader(r, 5, 17)
        
        buf := make([]byte, 9)
        if _, err := s.Read(buf); err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%s\n", buf)
        
        

        Output:

        io.Reader
        

        func (*SectionReader) ReadAt

        func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error)

        Example

        Code:

        r := strings.NewReader("some io.Reader stream to be read\n")
        s := io.NewSectionReader(r, 5, 17)
        
        buf := make([]byte, 6)
        if _, err := s.ReadAt(buf, 10); err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%s\n", buf)
        
        

        Output:

        stream
        

        func (*SectionReader) Seek

        func (s *SectionReader) Seek(offset int64, whence int) (int64, error)

        Example

        Code:

        r := strings.NewReader("some io.Reader stream to be read\n")
        s := io.NewSectionReader(r, 5, 17)
        
        if _, err := s.Seek(10, io.SeekStart); err != nil {
            log.Fatal(err)
        }
        
        if _, err := io.Copy(os.Stdout, s); err != nil {
            log.Fatal(err)
        }
        
        

        Output:

        stream
        

        func (*SectionReader) Size

        func (s *SectionReader) Size() int64

        Size returns the size of the section in bytes.

        Example

        Code:

        r := strings.NewReader("some io.Reader stream to be read\n")
        s := io.NewSectionReader(r, 5, 17)
        
        fmt.Println(s.Size())
        
        

        Output:

        17
        

        type Seeker

        Seeker is the interface that wraps the basic Seek method.

        Seek sets the offset for the next Read or Write to offset, interpreted according to whence: SeekStart means relative to the start of the file, SeekCurrent means relative to the current offset, and SeekEnd means relative to the end (for example, offset = -2 specifies the penultimate byte of the file). Seek returns the new offset relative to the start of the file or an error, if any.

        Seeking to an offset before the start of the file is an error. Seeking to any positive offset may be allowed, but if the new offset exceeds the size of the underlying object the behavior of subsequent I/O operations is implementation-dependent.

        type Seeker interface {
            Seek(offset int64, whence int) (int64, error)
        }

        type StringWriter

        StringWriter is the interface that wraps the WriteString method.

        type StringWriter interface {
            WriteString(s string) (n int, err error)
        }

        type WriteCloser

        WriteCloser is the interface that groups the basic Write and Close methods.

        type WriteCloser interface {
            Writer
            Closer
        }

        type WriteSeeker

        WriteSeeker is the interface that groups the basic Write and Seek methods.

        type WriteSeeker interface {
            Writer
            Seeker
        }

        type Writer

        Writer is the interface that wraps the basic Write method.

        Write writes len(p) bytes from p to the underlying data stream. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. Write must return a non-nil error if it returns n < len(p). Write must not modify the slice data, even temporarily.

        Implementations must not retain p.

        type Writer interface {
            Write(p []byte) (n int, err error)
        }

        Discard is a Writer on which all Write calls succeed without doing anything.

        var Discard Writer = discard{}

        func MultiWriter

        func MultiWriter(writers ...Writer) Writer

        MultiWriter creates a writer that duplicates its writes to all the provided writers, similar to the Unix tee(1) command.

        Each write is written to each listed writer, one at a time. If a listed writer returns an error, that overall write operation stops and returns the error; it does not continue down the list.

        Example

        Code:

        r := strings.NewReader("some io.Reader stream to be read\n")
        
        var buf1, buf2 strings.Builder
        w := io.MultiWriter(&buf1, &buf2)
        
        if _, err := io.Copy(w, r); err != nil {
            log.Fatal(err)
        }
        
        fmt.Print(buf1.String())
        fmt.Print(buf2.String())
        
        

        Output:

        some io.Reader stream to be read
        some io.Reader stream to be read
        

        type WriterAt

        WriterAt is the interface that wraps the basic WriteAt method.

        WriteAt writes len(p) bytes from p to the underlying data stream at offset off. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. WriteAt must return a non-nil error if it returns n < len(p).

        If WriteAt is writing to a destination with a seek offset, WriteAt should not affect nor be affected by the underlying seek offset.

        Clients of WriteAt can execute parallel WriteAt calls on the same destination if the ranges do not overlap.

        Implementations must not retain p.

        type WriterAt interface {
            WriteAt(p []byte, off int64) (n int, err error)
        }

        type WriterTo

        WriterTo is the interface that wraps the WriteTo method.

        WriteTo writes data to w until there's no more data to write or when an error occurs. The return value n is the number of bytes written. Any error encountered during the write is also returned.

        The Copy function uses WriterTo if available.

        type WriterTo interface {
            WriteTo(w Writer) (n int64, err error)
        }

        Subdirectories

        Name Synopsis
        ..
        fs Package fs defines basic interfaces to a file system.
        ioutil Package ioutil implements some I/O utility functions.
        fs - Go Documentation Server
        ...

        Package fs

        import "io/fs"
        Overview
        Index
        Examples

        Overview ▾

        Package fs defines basic interfaces to a file system. A file system can be provided by the host operating system but also by other packages.

        See the testing/fstest package for support with testing implementations of file systems.

        Variables

        Generic file system errors. Errors returned by file systems can be tested against these errors using errors.Is.

        var (
            ErrInvalid    = errInvalid()    // "invalid argument"
            ErrPermission = errPermission() // "permission denied"
            ErrExist      = errExist()      // "file already exists"
            ErrNotExist   = errNotExist()   // "file does not exist"
            ErrClosed     = errClosed()     // "file already closed"
        )

        SkipAll is used as a return value from WalkDirFunc to indicate that all remaining files and directories are to be skipped. It is not returned as an error by any function.

        var SkipAll = errors.New("skip everything and stop the walk")

        SkipDir is used as a return value from WalkDirFunc to indicate that the directory named in the call is to be skipped. It is not returned as an error by any function.

        var SkipDir = errors.New("skip this directory")

        func FormatDirEntry

        func FormatDirEntry(dir DirEntry) string

        FormatDirEntry returns a formatted version of dir for human readability. Implementations of DirEntry can call this from a String method. The outputs for a directory named subdir and a file named hello.go are:

        d subdir/
        - hello.go
        

        func FormatFileInfo

        func FormatFileInfo(info FileInfo) string

        FormatFileInfo returns a formatted version of info for human readability. Implementations of FileInfo can call this from a String method. The output for a file named "hello.go", 100 bytes, mode 0o644, created January 1, 1970 at noon is

        -rw-r--r-- 100 1970-01-01 12:00:00 hello.go
        

        func Glob

        func Glob(fsys FS, pattern string) (matches []string, err error)

        Glob returns the names of all files matching pattern or nil if there is no matching file. The syntax of patterns is the same as in path.Match. The pattern may describe hierarchical names such as usr/*/bin/ed.

        Glob ignores file system errors such as I/O errors reading directories. The only possible returned error is path.ErrBadPattern, reporting that the pattern is malformed.

        If fs implements GlobFS, Glob calls fs.Glob. Otherwise, Glob uses ReadDir to traverse the directory tree and look for matches for the pattern.

        func ReadFile

        func ReadFile(fsys FS, name string) ([]byte, error)

        ReadFile reads the named file from the file system fs and returns its contents. A successful call returns a nil error, not io.EOF. (Because ReadFile reads the whole file, the expected EOF from the final Read is not treated as an error to be reported.)

        If fs implements ReadFileFS, ReadFile calls fs.ReadFile. Otherwise ReadFile calls fs.Open and uses Read and Close on the returned File.

        func ValidPath

        func ValidPath(name string) bool

        ValidPath reports whether the given path name is valid for use in a call to Open.

        Path names passed to open are UTF-8-encoded, unrooted, slash-separated sequences of path elements, like “x/y/z”. Path names must not contain an element that is “.” or “..” or the empty string, except for the special case that the root directory is named “.”. Paths must not start or end with a slash: “/x” and “x/” are invalid.

        Note that paths are slash-separated on all systems, even Windows. Paths containing other characters such as backslash and colon are accepted as valid, but those characters must never be interpreted by an FS implementation as path element separators.

        func WalkDir

        func WalkDir(fsys FS, root string, fn WalkDirFunc) error

        WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.

        All errors that arise visiting files and directories are filtered by fn: see the fs.WalkDirFunc documentation for details.

        The files are walked in lexical order, which makes the output deterministic but requires WalkDir to read an entire directory into memory before proceeding to walk that directory.

        WalkDir does not follow symbolic links found in directories, but if root itself is a symbolic link, its target will be walked.

        Example

        Code:

        root := "/usr/local/go/bin"
        fileSystem := os.DirFS(root)
        
        fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
            if err != nil {
                log.Fatal(err)
            }
            fmt.Println(path)
            return nil
        })
        

        type DirEntry

        A DirEntry is an entry read from a directory (using the ReadDir function or a ReadDirFile's ReadDir method).

        type DirEntry interface {
            // Name returns the name of the file (or subdirectory) described by the entry.
            // This name is only the final element of the path (the base name), not the entire path.
            // For example, Name would return "hello.go" not "home/gopher/hello.go".
            Name() string
        
            // IsDir reports whether the entry describes a directory.
            IsDir() bool
        
            // Type returns the type bits for the entry.
            // The type bits are a subset of the usual FileMode bits, those returned by the FileMode.Type method.
            Type() FileMode
        
            // Info returns the FileInfo for the file or subdirectory described by the entry.
            // The returned FileInfo may be from the time of the original directory read
            // or from the time of the call to Info. If the file has been removed or renamed
            // since the directory read, Info may return an error satisfying errors.Is(err, ErrNotExist).
            // If the entry denotes a symbolic link, Info reports the information about the link itself,
            // not the link's target.
            Info() (FileInfo, error)
        }

        func FileInfoToDirEntry

        func FileInfoToDirEntry(info FileInfo) DirEntry

        FileInfoToDirEntry returns a DirEntry that returns information from info. If info is nil, FileInfoToDirEntry returns nil.

        func ReadDir

        func ReadDir(fsys FS, name string) ([]DirEntry, error)

        ReadDir reads the named directory and returns a list of directory entries sorted by filename.

        If fs implements ReadDirFS, ReadDir calls fs.ReadDir. Otherwise ReadDir calls fs.Open and uses ReadDir and Close on the returned file.

        type FS

        An FS provides access to a hierarchical file system.

        The FS interface is the minimum implementation required of the file system. A file system may implement additional interfaces, such as ReadFileFS, to provide additional or optimized functionality.

        testing/fstest.TestFS may be used to test implementations of an FS for correctness.

        type FS interface {
            // Open opens the named file.
            //
            // When Open returns an error, it should be of type *PathError
            // with the Op field set to "open", the Path field set to name,
            // and the Err field describing the problem.
            //
            // Open should reject attempts to open names that do not satisfy
            // ValidPath(name), returning a *PathError with Err set to
            // ErrInvalid or ErrNotExist.
            Open(name string) (File, error)
        }

        func Sub

        func Sub(fsys FS, dir string) (FS, error)

        Sub returns an FS corresponding to the subtree rooted at fsys's dir.

        If dir is ".", Sub returns fsys unchanged. Otherwise, if fs implements SubFS, Sub returns fsys.Sub(dir). Otherwise, Sub returns a new FS implementation sub that, in effect, implements sub.Open(name) as fsys.Open(path.Join(dir, name)). The implementation also translates calls to ReadDir, ReadFile, and Glob appropriately.

        Note that Sub(os.DirFS("/"), "prefix") is equivalent to os.DirFS("/prefix") and that neither of them guarantees to avoid operating system accesses outside "/prefix", because the implementation of os.DirFS does not check for symbolic links inside "/prefix" that point to other directories. That is, os.DirFS is not a general substitute for a chroot-style security mechanism, and Sub does not change that fact.

        type File

        A File provides access to a single file. The File interface is the minimum implementation required of the file. Directory files should also implement ReadDirFile. A file may implement io.ReaderAt or io.Seeker as optimizations.

        type File interface {
            Stat() (FileInfo, error)
            Read([]byte) (int, error)
            Close() error
        }

        type FileInfo

        A FileInfo describes a file and is returned by Stat.

        type FileInfo interface {
            Name() string       // base name of the file
            Size() int64        // length in bytes for regular files; system-dependent for others
            Mode() FileMode     // file mode bits
            ModTime() time.Time // modification time
            IsDir() bool        // abbreviation for Mode().IsDir()
            Sys() any           // underlying data source (can return nil)
        }

        func Stat

        func Stat(fsys FS, name string) (FileInfo, error)

        Stat returns a FileInfo describing the named file from the file system.

        If fs implements StatFS, Stat calls fs.Stat. Otherwise, Stat opens the File to stat it.

        type FileMode

        A FileMode represents a file's mode and permission bits. The bits have the same definition on all systems, so that information about files can be moved from one system to another portably. Not all bits apply to all systems. The only required bit is ModeDir for directories.

        type FileMode uint32

        The defined file mode bits are the most significant bits of the FileMode. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

        const (
            // The single letters are the abbreviations
            // used by the String method's formatting.
            ModeDir        FileMode = 1 << (32 - 1 - iota) // d: is a directory
            ModeAppend                                     // a: append-only
            ModeExclusive                                  // l: exclusive use
            ModeTemporary                                  // T: temporary file; Plan 9 only
            ModeSymlink                                    // L: symbolic link
            ModeDevice                                     // D: device file
            ModeNamedPipe                                  // p: named pipe (FIFO)
            ModeSocket                                     // S: Unix domain socket
            ModeSetuid                                     // u: setuid
            ModeSetgid                                     // g: setgid
            ModeCharDevice                                 // c: Unix character device, when ModeDevice is set
            ModeSticky                                     // t: sticky
            ModeIrregular                                  // ?: non-regular file; nothing else is known about this file
        
            // Mask for the type bits. For regular files, none will be set.
            ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice | ModeCharDevice | ModeIrregular
        
            ModePerm FileMode = 0777 // Unix permission bits
        )

        func (FileMode) IsDir

        func (m FileMode) IsDir() bool

        IsDir reports whether m describes a directory. That is, it tests for the ModeDir bit being set in m.

        func (FileMode) IsRegular

        func (m FileMode) IsRegular() bool

        IsRegular reports whether m describes a regular file. That is, it tests that no mode type bits are set.

        func (FileMode) Perm

        func (m FileMode) Perm() FileMode

        Perm returns the Unix permission bits in m (m & ModePerm).

        func (FileMode) String

        func (m FileMode) String() string

        func (FileMode) Type

        func (m FileMode) Type() FileMode

        Type returns type bits in m (m & ModeType).

        type GlobFS

        A GlobFS is a file system with a Glob method.

        type GlobFS interface {
            FS
        
            // Glob returns the names of all files matching pattern,
            // providing an implementation of the top-level
            // Glob function.
            Glob(pattern string) ([]string, error)
        }

        type PathError

        PathError records an error and the operation and file path that caused it.

        type PathError struct {
            Op   string
            Path string
            Err  error
        }
        

        func (*PathError) Error

        func (e *PathError) Error() string

        func (*PathError) Timeout

        func (e *PathError) Timeout() bool

        Timeout reports whether this error represents a timeout.

        func (*PathError) Unwrap

        func (e *PathError) Unwrap() error

        type ReadDirFS

        ReadDirFS is the interface implemented by a file system that provides an optimized implementation of ReadDir.

        type ReadDirFS interface {
            FS
        
            // ReadDir reads the named directory
            // and returns a list of directory entries sorted by filename.
            ReadDir(name string) ([]DirEntry, error)
        }

        type ReadDirFile

        A ReadDirFile is a directory file whose entries can be read with the ReadDir method. Every directory file should implement this interface. (It is permissible for any file to implement this interface, but if so ReadDir should return an error for non-directories.)

        type ReadDirFile interface {
            File
        
            // ReadDir reads the contents of the directory and returns
            // a slice of up to n DirEntry values in directory order.
            // Subsequent calls on the same file will yield further DirEntry values.
            //
            // If n > 0, ReadDir returns at most n DirEntry structures.
            // In this case, if ReadDir returns an empty slice, it will return
            // a non-nil error explaining why.
            // At the end of a directory, the error is io.EOF.
            // (ReadDir must return io.EOF itself, not an error wrapping io.EOF.)
            //
            // If n <= 0, ReadDir returns all the DirEntry values from the directory
            // in a single slice. In this case, if ReadDir succeeds (reads all the way
            // to the end of the directory), it returns the slice and a nil error.
            // If it encounters an error before the end of the directory,
            // ReadDir returns the DirEntry list read until that point and a non-nil error.
            ReadDir(n int) ([]DirEntry, error)
        }

        type ReadFileFS

        ReadFileFS is the interface implemented by a file system that provides an optimized implementation of ReadFile.

        type ReadFileFS interface {
            FS
        
            // ReadFile reads the named file and returns its contents.
            // A successful call returns a nil error, not io.EOF.
            // (Because ReadFile reads the whole file, the expected EOF
            // from the final Read is not treated as an error to be reported.)
            //
            // The caller is permitted to modify the returned byte slice.
            // This method should return a copy of the underlying data.
            ReadFile(name string) ([]byte, error)
        }

        type StatFS

        A StatFS is a file system with a Stat method.

        type StatFS interface {
            FS
        
            // Stat returns a FileInfo describing the file.
            // If there is an error, it should be of type *PathError.
            Stat(name string) (FileInfo, error)
        }

        type SubFS

        A SubFS is a file system with a Sub method.

        type SubFS interface {
            FS
        
            // Sub returns an FS corresponding to the subtree rooted at dir.
            Sub(dir string) (FS, error)
        }

        type WalkDirFunc

        WalkDirFunc is the type of the function called by WalkDir to visit each file or directory.

        The path argument contains the argument to WalkDir as a prefix. That is, if WalkDir is called with root argument "dir" and finds a file named "a" in that directory, the walk function will be called with argument "dir/a".

        The d argument is the DirEntry for the named path.

        The error result returned by the function controls how WalkDir continues. If the function returns the special value SkipDir, WalkDir skips the current directory (path if d.IsDir() is true, otherwise path's parent directory). If the function returns the special value SkipAll, WalkDir skips all remaining files and directories. Otherwise, if the function returns a non-nil error, WalkDir stops entirely and returns that error.

        The err argument reports an error related to path, signaling that WalkDir will not walk into that directory. The function can decide how to handle that error; as described earlier, returning the error will cause WalkDir to stop walking the entire tree.

        WalkDir calls the function with a non-nil err argument in two cases.

        First, if the initial Stat on the root directory fails, WalkDir calls the function with path set to root, d set to nil, and err set to the error from fs.Stat.

        Second, if a directory's ReadDir method (see ReadDirFile) fails, WalkDir calls the function with path set to the directory's path, d set to an DirEntry describing the directory, and err set to the error from ReadDir. In this second case, the function is called twice with the path of the directory: the first call is before the directory read is attempted and has err set to nil, giving the function a chance to return SkipDir or SkipAll and avoid the ReadDir entirely. The second call is after a failed ReadDir and reports the error from ReadDir. (If ReadDir succeeds, there is no second call.)

        The differences between WalkDirFunc compared to path/filepath.WalkFunc are:

        • The second argument has type DirEntry instead of FileInfo.
        • The function is called before reading a directory, to allow SkipDir or SkipAll to bypass the directory read entirely or skip all remaining files and directories respectively.
        • If a directory read fails, the function is called a second time for that directory to report the error.
        type WalkDirFunc func(path string, d DirEntry, err error) error
        ioutil - Go Documentation Server
        ...

        Package ioutil

        import "io/ioutil"
        Overview
        Index
        Examples

        Overview ▾

        Package ioutil implements some I/O utility functions.

        Deprecated: As of Go 1.16, the same functionality is now provided by package io or package os, and those implementations should be preferred in new code. See the specific function documentation for details.

        Variables

        Discard is an io.Writer on which all Write calls succeed without doing anything.

        Deprecated: As of Go 1.16, this value is simply io.Discard.

        var Discard io.Writer = io.Discard

        func NopCloser

        func NopCloser(r io.Reader) io.ReadCloser

        NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r.

        Deprecated: As of Go 1.16, this function simply calls io.NopCloser.

        func ReadAll

        func ReadAll(r io.Reader) ([]byte, error)

        ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.

        Deprecated: As of Go 1.16, this function simply calls io.ReadAll.

        Example

        Code:

        r := strings.NewReader("Go is a general-purpose language designed with systems programming in mind.")
        
        b, err := ioutil.ReadAll(r)
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%s", b)
        
        

        Output:

        Go is a general-purpose language designed with systems programming in mind.
        

        func ReadDir

        func ReadDir(dirname string) ([]fs.FileInfo, error)

        ReadDir reads the directory named by dirname and returns a list of fs.FileInfo for the directory's contents, sorted by filename. If an error occurs reading the directory, ReadDir returns no directory entries along with the error.

        Deprecated: As of Go 1.16, os.ReadDir is a more efficient and correct choice: it returns a list of fs.DirEntry instead of fs.FileInfo, and it returns partial results in the case of an error midway through reading a directory.

        If you must continue obtaining a list of fs.FileInfo, you still can:

        entries, err := os.ReadDir(dirname)
        if err != nil { ... }
        infos := make([]fs.FileInfo, 0, len(entries))
        for _, entry := range entries {
        	info, err := entry.Info()
        	if err != nil { ... }
        	infos = append(infos, info)
        }
        

        Example

        Code:

        files, err := ioutil.ReadDir(".")
        if err != nil {
            log.Fatal(err)
        }
        
        for _, file := range files {
            fmt.Println(file.Name())
        }
        

        func ReadFile

        func ReadFile(filename string) ([]byte, error)

        ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

        Deprecated: As of Go 1.16, this function simply calls os.ReadFile.

        Example

        Code:

        content, err := ioutil.ReadFile("testdata/hello")
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("File contents: %s", content)
        
        

        Output:

        File contents: Hello, Gophers!
        

        func TempDir

        func TempDir(dir, pattern string) (name string, err error)

        TempDir creates a new temporary directory in the directory dir. The directory name is generated by taking pattern and applying a random string to the end. If pattern includes a "*", the random string replaces the last "*". TempDir returns the name of the new directory. If dir is the empty string, TempDir uses the default directory for temporary files (see os.TempDir). Multiple programs calling TempDir simultaneously will not choose the same directory. It is the caller's responsibility to remove the directory when no longer needed.

        Deprecated: As of Go 1.17, this function simply calls os.MkdirTemp.

        Example

        Code:

        content := []byte("temporary file's content")
        dir, err := ioutil.TempDir("", "example")
        if err != nil {
            log.Fatal(err)
        }
        
        defer os.RemoveAll(dir) // clean up
        
        tmpfn := filepath.Join(dir, "tmpfile")
        if err := ioutil.WriteFile(tmpfn, content, 0666); err != nil {
            log.Fatal(err)
        }
        

        Example (Suffix)

        Code:

        parentDir := os.TempDir()
        logsDir, err := ioutil.TempDir(parentDir, "*-logs")
        if err != nil {
            log.Fatal(err)
        }
        defer os.RemoveAll(logsDir) // clean up
        
        // Logs can be cleaned out earlier if needed by searching
        // for all directories whose suffix ends in *-logs.
        globPattern := filepath.Join(parentDir, "*-logs")
        matches, err := filepath.Glob(globPattern)
        if err != nil {
            log.Fatalf("Failed to match %q: %v", globPattern, err)
        }
        
        for _, match := range matches {
            if err := os.RemoveAll(match); err != nil {
                log.Printf("Failed to remove %q: %v", match, err)
            }
        }
        

        func TempFile

        func TempFile(dir, pattern string) (f *os.File, err error)

        TempFile creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting *os.File. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a "*", the random string replaces the last "*". If dir is the empty string, TempFile uses the default directory for temporary files (see os.TempDir). Multiple programs calling TempFile simultaneously will not choose the same file. The caller can use f.Name() to find the pathname of the file. It is the caller's responsibility to remove the file when no longer needed.

        Deprecated: As of Go 1.17, this function simply calls os.CreateTemp.

        Example

        Code:

        content := []byte("temporary file's content")
        tmpfile, err := ioutil.TempFile("", "example")
        if err != nil {
            log.Fatal(err)
        }
        
        defer os.Remove(tmpfile.Name()) // clean up
        
        if _, err := tmpfile.Write(content); err != nil {
            log.Fatal(err)
        }
        if err := tmpfile.Close(); err != nil {
            log.Fatal(err)
        }
        

        Example (Suffix)

        Code:

        content := []byte("temporary file's content")
        tmpfile, err := ioutil.TempFile("", "example.*.txt")
        if err != nil {
            log.Fatal(err)
        }
        
        defer os.Remove(tmpfile.Name()) // clean up
        
        if _, err := tmpfile.Write(content); err != nil {
            tmpfile.Close()
            log.Fatal(err)
        }
        if err := tmpfile.Close(); err != nil {
            log.Fatal(err)
        }
        

        func WriteFile

        func WriteFile(filename string, data []byte, perm fs.FileMode) error

        WriteFile writes data to a file named by filename. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions.

        Deprecated: As of Go 1.16, this function simply calls os.WriteFile.

        Example

        Code:

        message := []byte("Hello, Gophers!")
        err := ioutil.WriteFile("hello", message, 0644)
        if err != nil {
            log.Fatal(err)
        }
        
        iter - Go Documentation Server
        ...

        Command iter

        Package iter provides basic definitions and operations related to iteration in Go.

        This package is experimental and can only be imported when building with GOEXPERIMENT=rangefunc.

        slog - Go Documentation Server
        ...

        Package slog

        Overview ▾

        Package slog provides structured logging, in which log records include a message, a severity level, and various other attributes expressed as key-value pairs.

        It defines a type, Logger, which provides several methods (such as Logger.Info and Logger.Error) for reporting events of interest.

        Each Logger is associated with a Handler. A Logger output method creates a Record from the method arguments and passes it to the Handler, which decides how to handle it. There is a default Logger accessible through top-level functions (such as Info and Error) that call the corresponding Logger methods.

        A log record consists of a time, a level, a message, and a set of key-value pairs, where the keys are strings and the values may be of any type. As an example,

        slog.Info("hello", "count", 3)
        

        creates a record containing the time of the call, a level of Info, the message "hello", and a single pair with key "count" and value 3.

        The Info top-level function calls the Logger.Info method on the default Logger. In addition to Logger.Info, there are methods for Debug, Warn and Error levels. Besides these convenience methods for common levels, there is also a Logger.Log method which takes the level as an argument. Each of these methods has a corresponding top-level function that uses the default logger.

        The default handler formats the log record's message, time, level, and attributes as a string and passes it to the log package.

        2022/11/08 15:28:26 INFO hello count=3
        

        For more control over the output format, create a logger with a different handler. This statement uses New to create a new logger with a TextHandler that writes structured records in text form to standard error:

        logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
        

        TextHandler output is a sequence of key=value pairs, easily and unambiguously parsed by machine. This statement:

        logger.Info("hello", "count", 3)
        

        produces this output:

        time=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3
        

        The package also provides JSONHandler, whose output is line-delimited JSON:

        logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
        logger.Info("hello", "count", 3)
        

        produces this output:

        {"time":"2022-11-08T15:28:26.000000000-05:00","level":"INFO","msg":"hello","count":3}
        

        Both TextHandler and JSONHandler can be configured with HandlerOptions. There are options for setting the minimum level (see Levels, below), displaying the source file and line of the log call, and modifying attributes before they are logged.

        Setting a logger as the default with

        slog.SetDefault(logger)
        

        will cause the top-level functions like Info to use it. SetDefault also updates the default logger used by the log package, so that existing applications that use log.Printf and related functions will send log records to the logger's handler without needing to be rewritten.

        Some attributes are common to many log calls. For example, you may wish to include the URL or trace identifier of a server request with all log events arising from the request. Rather than repeat the attribute with every log call, you can use Logger.With to construct a new Logger containing the attributes:

        logger2 := logger.With("url", r.URL)
        

        The arguments to With are the same key-value pairs used in Logger.Info. The result is a new Logger with the same handler as the original, but additional attributes that will appear in the output of every call.

        Levels

        A Level is an integer representing the importance or severity of a log event. The higher the level, the more severe the event. This package defines constants for the most common levels, but any int can be used as a level.

        In an application, you may wish to log messages only at a certain level or greater. One common configuration is to log messages at Info or higher levels, suppressing debug logging until it is needed. The built-in handlers can be configured with the minimum level to output by setting [HandlerOptions.Level]. The program's `main` function typically does this. The default value is LevelInfo.

        Setting the [HandlerOptions.Level] field to a Level value fixes the handler's minimum level throughout its lifetime. Setting it to a LevelVar allows the level to be varied dynamically. A LevelVar holds a Level and is safe to read or write from multiple goroutines. To vary the level dynamically for an entire program, first initialize a global LevelVar:

        var programLevel = new(slog.LevelVar) // Info by default
        

        Then use the LevelVar to construct a handler, and make it the default:

        h := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel})
        slog.SetDefault(slog.New(h))
        

        Now the program can change its logging level with a single statement:

        programLevel.Set(slog.LevelDebug)
        

        Groups

        Attributes can be collected into groups. A group has a name that is used to qualify the names of its attributes. How this qualification is displayed depends on the handler. TextHandler separates the group and attribute names with a dot. JSONHandler treats each group as a separate JSON object, with the group name as the key.

        Use Group to create a Group attribute from a name and a list of key-value pairs:

        slog.Group("request",
            "method", r.Method,
            "url", r.URL)
        

        TextHandler would display this group as

        request.method=GET request.url=http://example.com
        

        JSONHandler would display it as

        "request":{"method":"GET","url":"http://example.com"}
        

        Use Logger.WithGroup to qualify all of a Logger's output with a group name. Calling WithGroup on a Logger results in a new Logger with the same Handler as the original, but with all its attributes qualified by the group name.

        This can help prevent duplicate attribute keys in large systems, where subsystems might use the same keys. Pass each subsystem a different Logger with its own group name so that potential duplicates are qualified:

        logger := slog.Default().With("id", systemID)
        parserLogger := logger.WithGroup("parser")
        parseInput(input, parserLogger)
        

        When parseInput logs with parserLogger, its keys will be qualified with "parser", so even if it uses the common key "id", the log line will have distinct keys.

        Contexts

        Some handlers may wish to include information from the context.Context that is available at the call site. One example of such information is the identifier for the current span when tracing is enabled.

        The Logger.Log and Logger.LogAttrs methods take a context as a first argument, as do their corresponding top-level functions.

        Although the convenience methods on Logger (Info and so on) and the corresponding top-level functions do not take a context, the alternatives ending in "Context" do. For example,

        slog.InfoContext(ctx, "message")
        

        It is recommended to pass a context to an output method if one is available.

        Attrs and Values

        An Attr is a key-value pair. The Logger output methods accept Attrs as well as alternating keys and values. The statement

        slog.Info("hello", slog.Int("count", 3))
        

        behaves the same as

        slog.Info("hello", "count", 3)
        

        There are convenience constructors for Attr such as Int, String, and Bool for common types, as well as the function Any for constructing Attrs of any type.

        The value part of an Attr is a type called Value. Like an [any], a Value can hold any Go value, but it can represent typical values, including all numbers and strings, without an allocation.

        For the most efficient log output, use Logger.LogAttrs. It is similar to Logger.Log but accepts only Attrs, not alternating keys and values; this allows it, too, to avoid allocation.

        The call

        logger.LogAttrs(ctx, slog.LevelInfo, "hello", slog.Int("count", 3))
        

        is the most efficient way to achieve the same output as

        slog.InfoContext(ctx, "hello", "count", 3)
        

        Customizing a type's logging behavior

        If a type implements the LogValuer interface, the Value returned from its LogValue method is used for logging. You can use this to control how values of the type appear in logs. For example, you can redact secret information like passwords, or gather a struct's fields in a Group. See the examples under LogValuer for details.

        A LogValue method may return a Value that itself implements LogValuer. The Value.Resolve method handles these cases carefully, avoiding infinite loops and unbounded recursion. Handler authors and others may wish to use Value.Resolve instead of calling LogValue directly.

        Wrapping output methods

        The logger functions use reflection over the call stack to find the file name and line number of the logging call within the application. This can produce incorrect source information for functions that wrap slog. For instance, if you define this function in file mylog.go:

        func Infof(logger *slog.Logger, format string, args ...any) {
            logger.Info(fmt.Sprintf(format, args...))
        }
        

        and you call it like this in main.go:

        Infof(slog.Default(), "hello, %s", "world")
        

        then slog will report the source file as mylog.go, not main.go.

        A correct implementation of Infof will obtain the source location (pc) and pass it to NewRecord. The Infof function in the package-level example called "wrapping" demonstrates how to do this.

        Working with Records

        Sometimes a Handler will need to modify a Record before passing it on to another Handler or backend. A Record contains a mixture of simple public fields (e.g. Time, Level, Message) and hidden fields that refer to state (such as attributes) indirectly. This means that modifying a simple copy of a Record (e.g. by calling Record.Add or Record.AddAttrs to add attributes) may have unexpected effects on the original. Before modifying a Record, use Record.Clone to create a copy that shares no state with the original, or create a new Record with NewRecord and build up its Attrs by traversing the old ones with Record.Attrs.

        Performance considerations

        If profiling your application demonstrates that logging is taking significant time, the following suggestions may help.

        If many log lines have a common attribute, use Logger.With to create a Logger with that attribute. The built-in handlers will format that attribute only once, at the call to Logger.With. The Handler interface is designed to allow that optimization, and a well-written Handler should take advantage of it.

        The arguments to a log call are always evaluated, even if the log event is discarded. If possible, defer computation so that it happens only if the value is actually logged. For example, consider the call

        slog.Info("starting request", "url", r.URL.String())  // may compute String unnecessarily
        

        The URL.String method will be called even if the logger discards Info-level events. Instead, pass the URL directly:

        slog.Info("starting request", "url", &r.URL) // calls URL.String only if needed
        

        The built-in TextHandler will call its String method, but only if the log event is enabled. Avoiding the call to String also preserves the structure of the underlying value. For example JSONHandler emits the components of the parsed URL as a JSON object. If you want to avoid eagerly paying the cost of the String call without causing the handler to potentially inspect the structure of the value, wrap the value in a fmt.Stringer implementation that hides its Marshal methods.

        You can also use the LogValuer interface to avoid unnecessary work in disabled log calls. Say you need to log some expensive value:

        slog.Debug("frobbing", "value", computeExpensiveValue(arg))
        

        Even if this line is disabled, computeExpensiveValue will be called. To avoid that, define a type implementing LogValuer:

        type expensive struct { arg int }
        
        func (e expensive) LogValue() slog.Value {
            return slog.AnyValue(computeExpensiveValue(e.arg))
        }
        

        Then use a value of that type in log calls:

        slog.Debug("frobbing", "value", expensive{arg})
        

        Now computeExpensiveValue will only be called when the line is enabled.

        The built-in handlers acquire a lock before calling io.Writer.Write to ensure that each record is written in one piece. User-defined handlers are responsible for their own locking.

        Writing a handler

        For a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide.

        Example (Wrapping)

        Code:

        package slog_test
        
        import (
            "context"
            "fmt"
            "log/slog"
            "os"
            "path/filepath"
            "runtime"
            "time"
        )
        
        // Infof is an example of a user-defined logging function that wraps slog.
        // The log record contains the source position of the caller of Infof.
        func Infof(logger *slog.Logger, format string, args ...any) {
            if !logger.Enabled(context.Background(), slog.LevelInfo) {
                return
            }
            var pcs [1]uintptr
            runtime.Callers(2, pcs[:]) // skip [Callers, Infof]
            r := slog.NewRecord(time.Now(), slog.LevelInfo, fmt.Sprintf(format, args...), pcs[0])
            _ = logger.Handler().Handle(context.Background(), r)
        }
        
        func Example_wrapping() {
            replace := func(groups []string, a slog.Attr) slog.Attr {
                // Remove time.
                if a.Key == slog.TimeKey && len(groups) == 0 {
                    return slog.Attr{}
                }
                // Remove the directory from the source's filename.
                if a.Key == slog.SourceKey {
                    source := a.Value.Any().(*slog.Source)
                    source.File = filepath.Base(source.File)
                }
                return a
            }
            logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
            Infof(logger, "message, %s", "formatted")
        
            // Output:
            // level=INFO source=example_wrap_test.go:43 msg="message, formatted"
        }
        

        Index ▾

        Constants
        func Debug(msg string, args ...any)
        func DebugContext(ctx context.Context, msg string, args ...any)
        func Error(msg string, args ...any)
        func ErrorContext(ctx context.Context, msg string, args ...any)
        func Info(msg string, args ...any)
        func InfoContext(ctx context.Context, msg string, args ...any)
        func Log(ctx context.Context, level Level, msg string, args ...any)
        func LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)
        func NewLogLogger(h Handler, level Level) *log.Logger
        func SetDefault(l *Logger)
        func Warn(msg string, args ...any)
        func WarnContext(ctx context.Context, msg string, args ...any)
        type Attr
            func Any(key string, value any) Attr
            func Bool(key string, v bool) Attr
            func Duration(key string, v time.Duration) Attr
            func Float64(key string, v float64) Attr
            func Group(key string, args ...any) Attr
            func Int(key string, value int) Attr
            func Int64(key string, value int64) Attr
            func String(key, value string) Attr
            func Time(key string, v time.Time) Attr
            func Uint64(key string, v uint64) Attr
            func (a Attr) Equal(b Attr) bool
            func (a Attr) String() string
        type Handler
        type HandlerOptions
        type JSONHandler
            func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler
            func (h *JSONHandler) Enabled(_ context.Context, level Level) bool
            func (h *JSONHandler) Handle(_ context.Context, r Record) error
            func (h *JSONHandler) WithAttrs(attrs []Attr) Handler
            func (h *JSONHandler) WithGroup(name string) Handler
        type Kind
            func (k Kind) String() string
        type Level
            func SetLogLoggerLevel(level Level) (oldLevel Level)
            func (l Level) Level() Level
            func (l Level) MarshalJSON() ([]byte, error)
            func (l Level) MarshalText() ([]byte, error)
            func (l Level) String() string
            func (l *Level) UnmarshalJSON(data []byte) error
            func (l *Level) UnmarshalText(data []byte) error
        type LevelVar
            func (v *LevelVar) Level() Level
            func (v *LevelVar) MarshalText() ([]byte, error)
            func (v *LevelVar) Set(l Level)
            func (v *LevelVar) String() string
            func (v *LevelVar) UnmarshalText(data []byte) error
        type Leveler
        type LogValuer
        type Logger
            func Default() *Logger
            func New(h Handler) *Logger
            func With(args ...any) *Logger
            func (l *Logger) Debug(msg string, args ...any)
            func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any)
            func (l *Logger) Enabled(ctx context.Context, level Level) bool
            func (l *Logger) Error(msg string, args ...any)
            func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any)
            func (l *Logger) Handler() Handler
            func (l *Logger) Info(msg string, args ...any)
            func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any)
            func (l *Logger) Log(ctx context.Context, level Level, msg string, args ...any)
            func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)
            func (l *Logger) Warn(msg string, args ...any)
            func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any)
            func (l *Logger) With(args ...any) *Logger
            func (l *Logger) WithGroup(name string) *Logger
        type Record
            func NewRecord(t time.Time, level Level, msg string, pc uintptr) Record
            func (r *Record) Add(args ...any)
            func (r *Record) AddAttrs(attrs ...Attr)
            func (r Record) Attrs(f func(Attr) bool)
            func (r Record) Clone() Record
            func (r Record) NumAttrs() int
        type Source
        type TextHandler
            func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler
            func (h *TextHandler) Enabled(_ context.Context, level Level) bool
            func (h *TextHandler) Handle(_ context.Context, r Record) error
            func (h *TextHandler) WithAttrs(attrs []Attr) Handler
            func (h *TextHandler) WithGroup(name string) Handler
        type Value
            func AnyValue(v any) Value
            func BoolValue(v bool) Value
            func DurationValue(v time.Duration) Value
            func Float64Value(v float64) Value
            func GroupValue(as ...Attr) Value
            func Int64Value(v int64) Value
            func IntValue(v int) Value
            func StringValue(value string) Value
            func TimeValue(v time.Time) Value
            func Uint64Value(v uint64) Value
            func (v Value) Any() any
            func (v Value) Bool() bool
            func (v Value) Duration() time.Duration
            func (v Value) Equal(w Value) bool
            func (v Value) Float64() float64
            func (v Value) Group() []Attr
            func (v Value) Int64() int64
            func (v Value) Kind() Kind
            func (v Value) LogValuer() LogValuer
            func (v Value) Resolve() (rv Value)
            func (v Value) String() string
            func (v Value) Time() time.Time
            func (v Value) Uint64() uint64

        Package files

        attr.go doc.go handler.go json_handler.go level.go logger.go record.go text_handler.go value.go

        Constants

        Keys for "built-in" attributes.

        const (
            // TimeKey is the key used by the built-in handlers for the time
            // when the log method is called. The associated Value is a [time.Time].
            TimeKey = "time"
            // LevelKey is the key used by the built-in handlers for the level
            // of the log call. The associated value is a [Level].
            LevelKey = "level"
            // MessageKey is the key used by the built-in handlers for the
            // message of the log call. The associated value is a string.
            MessageKey = "msg"
            // SourceKey is the key used by the built-in handlers for the source file
            // and line of the log call. The associated value is a *[Source].
            SourceKey = "source"
        )

        func Debug

        func Debug(msg string, args ...any)

        Debug calls Logger.Debug on the default logger.

        func DebugContext

        func DebugContext(ctx context.Context, msg string, args ...any)

        DebugContext calls Logger.DebugContext on the default logger.

        func Error

        func Error(msg string, args ...any)

        Error calls Logger.Error on the default logger.

        func ErrorContext

        func ErrorContext(ctx context.Context, msg string, args ...any)

        ErrorContext calls Logger.ErrorContext on the default logger.

        func Info

        func Info(msg string, args ...any)

        Info calls Logger.Info on the default logger.

        func InfoContext

        func InfoContext(ctx context.Context, msg string, args ...any)

        InfoContext calls Logger.InfoContext on the default logger.

        func Log

        func Log(ctx context.Context, level Level, msg string, args ...any)

        Log calls Logger.Log on the default logger.

        func LogAttrs

        func LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)

        LogAttrs calls Logger.LogAttrs on the default logger.

        func NewLogLogger

        func NewLogLogger(h Handler, level Level) *log.Logger

        NewLogLogger returns a new log.Logger such that each call to its Output method dispatches a Record to the specified handler. The logger acts as a bridge from the older log API to newer structured logging handlers.

        func SetDefault

        func SetDefault(l *Logger)

        SetDefault makes l the default Logger, which is used by the top-level functions Info, Debug and so on. After this call, output from the log package's default Logger (as with log.Print, etc.) will be logged using l's Handler, at a level controlled by SetLogLoggerLevel.

        func Warn

        func Warn(msg string, args ...any)

        Warn calls Logger.Warn on the default logger.

        func WarnContext

        func WarnContext(ctx context.Context, msg string, args ...any)

        WarnContext calls Logger.WarnContext on the default logger.

        type Attr

        An Attr is a key-value pair.

        type Attr struct {
            Key   string
            Value Value
        }
        

        func Any

        func Any(key string, value any) Attr

        Any returns an Attr for the supplied value. See AnyValue for how values are treated.

        func Bool

        func Bool(key string, v bool) Attr

        Bool returns an Attr for a bool.

        func Duration

        func Duration(key string, v time.Duration) Attr

        Duration returns an Attr for a time.Duration.

        func Float64

        func Float64(key string, v float64) Attr

        Float64 returns an Attr for a floating-point number.

        func Group

        func Group(key string, args ...any) Attr

        Group returns an Attr for a Group Value. The first argument is the key; the remaining arguments are converted to Attrs as in Logger.Log.

        Use Group to collect several key-value pairs under a single key on a log line, or as the result of LogValue in order to log a single value as multiple Attrs.

        Example

        Code:

        r, _ := http.NewRequest("GET", "localhost", nil)
        // ...
        
        logger := slog.New(
            slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
                ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
                    if a.Key == slog.TimeKey && len(groups) == 0 {
                        return slog.Attr{}
                    }
                    return a
                },
            }),
        )
        logger.Info("finished",
            slog.Group("req",
                slog.String("method", r.Method),
                slog.String("url", r.URL.String())),
            slog.Int("status", http.StatusOK),
            slog.Duration("duration", time.Second))
        
        

        Output:

        level=INFO msg=finished req.method=GET req.url=localhost status=200 duration=1s
        

        func Int

        func Int(key string, value int) Attr

        Int converts an int to an int64 and returns an Attr with that value.

        func Int64

        func Int64(key string, value int64) Attr

        Int64 returns an Attr for an int64.

        func String

        func String(key, value string) Attr

        String returns an Attr for a string value.

        func Time

        func Time(key string, v time.Time) Attr

        Time returns an Attr for a time.Time. It discards the monotonic portion.

        func Uint64

        func Uint64(key string, v uint64) Attr

        Uint64 returns an Attr for a uint64.

        func (Attr) Equal

        func (a Attr) Equal(b Attr) bool

        Equal reports whether a and b have equal keys and values.

        func (Attr) String

        func (a Attr) String() string

        type Handler

        A Handler handles log records produced by a Logger.

        A typical handler may print log records to standard error, or write them to a file or database, or perhaps augment them with additional attributes and pass them on to another handler.

        Any of the Handler's methods may be called concurrently with itself or with other methods. It is the responsibility of the Handler to manage this concurrency.

        Users of the slog package should not invoke Handler methods directly. They should use the methods of Logger instead.

        type Handler interface {
            // Enabled reports whether the handler handles records at the given level.
            // The handler ignores records whose level is lower.
            // It is called early, before any arguments are processed,
            // to save effort if the log event should be discarded.
            // If called from a Logger method, the first argument is the context
            // passed to that method, or context.Background() if nil was passed
            // or the method does not take a context.
            // The context is passed so Enabled can use its values
            // to make a decision.
            Enabled(context.Context, Level) bool
        
            // Handle handles the Record.
            // It will only be called when Enabled returns true.
            // The Context argument is as for Enabled.
            // It is present solely to provide Handlers access to the context's values.
            // Canceling the context should not affect record processing.
            // (Among other things, log messages may be necessary to debug a
            // cancellation-related problem.)
            //
            // Handle methods that produce output should observe the following rules:
            //   - If r.Time is the zero time, ignore the time.
            //   - If r.PC is zero, ignore it.
            //   - Attr's values should be resolved.
            //   - If an Attr's key and value are both the zero value, ignore the Attr.
            //     This can be tested with attr.Equal(Attr{}).
            //   - If a group's key is empty, inline the group's Attrs.
            //   - If a group has no Attrs (even if it has a non-empty key),
            //     ignore it.
            Handle(context.Context, Record) error
        
            // WithAttrs returns a new Handler whose attributes consist of
            // both the receiver's attributes and the arguments.
            // The Handler owns the slice: it may retain, modify or discard it.
            WithAttrs(attrs []Attr) Handler
        
            // WithGroup returns a new Handler with the given group appended to
            // the receiver's existing groups.
            // The keys of all subsequent attributes, whether added by With or in a
            // Record, should be qualified by the sequence of group names.
            //
            // How this qualification happens is up to the Handler, so long as
            // this Handler's attribute keys differ from those of another Handler
            // with a different sequence of group names.
            //
            // A Handler should treat WithGroup as starting a Group of Attrs that ends
            // at the end of the log event. That is,
            //
            //     logger.WithGroup("s").LogAttrs(ctx, level, msg, slog.Int("a", 1), slog.Int("b", 2))
            //
            // should behave like
            //
            //     logger.LogAttrs(ctx, level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2)))
            //
            // If the name is empty, WithGroup returns the receiver.
            WithGroup(name string) Handler
        }

        Example (LevelHandler)

        This example shows how to Use a LevelHandler to change the level of an existing Handler while preserving its other behavior. This example demonstrates increasing the log level to reduce a logger's output. Another typical use would be to decrease the log level (to LevelDebug, say) during a part of the program that was suspected of containing a bug.

        Code:

        package slog_test
        
        import (
            "context"
            "log/slog"
            "log/slog/internal/slogtest"
            "os"
        )
        
        // A LevelHandler wraps a Handler with an Enabled method
        // that returns false for levels below a minimum.
        type LevelHandler struct {
            level   slog.Leveler
            handler slog.Handler
        }
        
        // NewLevelHandler returns a LevelHandler with the given level.
        // All methods except Enabled delegate to h.
        func NewLevelHandler(level slog.Leveler, h slog.Handler) *LevelHandler {
            // Optimization: avoid chains of LevelHandlers.
            if lh, ok := h.(*LevelHandler); ok {
                h = lh.Handler()
            }
            return &LevelHandler{level, h}
        }
        
        // Enabled implements Handler.Enabled by reporting whether
        // level is at least as large as h's level.
        func (h *LevelHandler) Enabled(_ context.Context, level slog.Level) bool {
            return level >= h.level.Level()
        }
        
        // Handle implements Handler.Handle.
        func (h *LevelHandler) Handle(ctx context.Context, r slog.Record) error {
            return h.handler.Handle(ctx, r)
        }
        
        // WithAttrs implements Handler.WithAttrs.
        func (h *LevelHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
            return NewLevelHandler(h.level, h.handler.WithAttrs(attrs))
        }
        
        // WithGroup implements Handler.WithGroup.
        func (h *LevelHandler) WithGroup(name string) slog.Handler {
            return NewLevelHandler(h.level, h.handler.WithGroup(name))
        }
        
        // Handler returns the Handler wrapped by h.
        func (h *LevelHandler) Handler() slog.Handler {
            return h.handler
        }
        
        // This example shows how to Use a LevelHandler to change the level of an
        // existing Handler while preserving its other behavior.
        //
        // This example demonstrates increasing the log level to reduce a logger's
        // output.
        //
        // Another typical use would be to decrease the log level (to LevelDebug, say)
        // during a part of the program that was suspected of containing a bug.
        func ExampleHandler_levelHandler() {
            th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime})
            logger := slog.New(NewLevelHandler(slog.LevelWarn, th))
            logger.Info("not printed")
            logger.Warn("printed")
        
            // Output:
            // level=WARN msg=printed
        }
        

        type HandlerOptions

        HandlerOptions are options for a TextHandler or JSONHandler. A zero HandlerOptions consists entirely of default values.

        type HandlerOptions struct {
            // AddSource causes the handler to compute the source code position
            // of the log statement and add a SourceKey attribute to the output.
            AddSource bool
        
            // Level reports the minimum record level that will be logged.
            // The handler discards records with lower levels.
            // If Level is nil, the handler assumes LevelInfo.
            // The handler calls Level.Level for each record processed;
            // to adjust the minimum level dynamically, use a LevelVar.
            Level Leveler
        
            // ReplaceAttr is called to rewrite each non-group attribute before it is logged.
            // The attribute's value has been resolved (see [Value.Resolve]).
            // If ReplaceAttr returns a zero Attr, the attribute is discarded.
            //
            // The built-in attributes with keys "time", "level", "source", and "msg"
            // are passed to this function, except that time is omitted
            // if zero, and source is omitted if AddSource is false.
            //
            // The first argument is a list of currently open groups that contain the
            // Attr. It must not be retained or modified. ReplaceAttr is never called
            // for Group attributes, only their contents. For example, the attribute
            // list
            //
            //     Int("a", 1), Group("g", Int("b", 2)), Int("c", 3)
            //
            // results in consecutive calls to ReplaceAttr with the following arguments:
            //
            //     nil, Int("a", 1)
            //     []string{"g"}, Int("b", 2)
            //     nil, Int("c", 3)
            //
            // ReplaceAttr can be used to change the default keys of the built-in
            // attributes, convert types (for example, to replace a `time.Time` with the
            // integer seconds since the Unix epoch), sanitize personal information, or
            // remove attributes from the output.
            ReplaceAttr func(groups []string, a Attr) Attr
        }
        

        Example (CustomLevels)

        This example demonstrates using custom log levels and custom log level names. In addition to the default log levels, it introduces Trace, Notice, and Emergency levels. The ReplaceAttr changes the way levels are printed for both the standard log levels and the custom log levels.

        Code:

        // Exported constants from a custom logging package.
        const (
            LevelTrace     = slog.Level(-8)
            LevelDebug     = slog.LevelDebug
            LevelInfo      = slog.LevelInfo
            LevelNotice    = slog.Level(2)
            LevelWarning   = slog.LevelWarn
            LevelError     = slog.LevelError
            LevelEmergency = slog.Level(12)
        )
        
        th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
            // Set a custom level to show all log output. The default value is
            // LevelInfo, which would drop Debug and Trace logs.
            Level: LevelTrace,
        
            ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
                // Remove time from the output for predictable test output.
                if a.Key == slog.TimeKey {
                    return slog.Attr{}
                }
        
                // Customize the name of the level key and the output string, including
                // custom level values.
                if a.Key == slog.LevelKey {
                    // Rename the level key from "level" to "sev".
                    a.Key = "sev"
        
                    // Handle custom level values.
                    level := a.Value.Any().(slog.Level)
        
                    // This could also look up the name from a map or other structure, but
                    // this demonstrates using a switch statement to rename levels. For
                    // maximum performance, the string values should be constants, but this
                    // example uses the raw strings for readability.
                    switch {
                    case level < LevelDebug:
                        a.Value = slog.StringValue("TRACE")
                    case level < LevelInfo:
                        a.Value = slog.StringValue("DEBUG")
                    case level < LevelNotice:
                        a.Value = slog.StringValue("INFO")
                    case level < LevelWarning:
                        a.Value = slog.StringValue("NOTICE")
                    case level < LevelError:
                        a.Value = slog.StringValue("WARNING")
                    case level < LevelEmergency:
                        a.Value = slog.StringValue("ERROR")
                    default:
                        a.Value = slog.StringValue("EMERGENCY")
                    }
                }
        
                return a
            },
        })
        
        logger := slog.New(th)
        ctx := context.Background()
        logger.Log(ctx, LevelEmergency, "missing pilots")
        logger.Error("failed to start engines", "err", "missing fuel")
        logger.Warn("falling back to default value")
        logger.Log(ctx, LevelNotice, "all systems are running")
        logger.Info("initiating launch")
        logger.Debug("starting background job")
        logger.Log(ctx, LevelTrace, "button clicked")
        
        

        Output:

        sev=EMERGENCY msg="missing pilots"
        sev=ERROR msg="failed to start engines" err="missing fuel"
        sev=WARNING msg="falling back to default value"
        sev=NOTICE msg="all systems are running"
        sev=INFO msg="initiating launch"
        sev=DEBUG msg="starting background job"
        sev=TRACE msg="button clicked"
        

        type JSONHandler

        JSONHandler is a Handler that writes Records to an io.Writer as line-delimited JSON objects.

        type JSONHandler struct {
            // contains filtered or unexported fields
        }
        

        func NewJSONHandler

        func NewJSONHandler(w io.Writer, opts *HandlerOptions) *JSONHandler

        NewJSONHandler creates a JSONHandler that writes to w, using the given options. If opts is nil, the default options are used.

        func (*JSONHandler) Enabled

        func (h *JSONHandler) Enabled(_ context.Context, level Level) bool

        Enabled reports whether the handler handles records at the given level. The handler ignores records whose level is lower.

        func (*JSONHandler) Handle

        func (h *JSONHandler) Handle(_ context.Context, r Record) error

        Handle formats its argument Record as a JSON object on a single line.

        If the Record's time is zero, the time is omitted. Otherwise, the key is "time" and the value is output as with json.Marshal.

        If the Record's level is zero, the level is omitted. Otherwise, the key is "level" and the value of Level.String is output.

        If the AddSource option is set and source information is available, the key is "source", and the value is a record of type Source.

        The message's key is "msg".

        To modify these or other attributes, or remove them from the output, use [HandlerOptions.ReplaceAttr].

        Values are formatted as with an encoding/json.Encoder with SetEscapeHTML(false), with two exceptions.

        First, an Attr whose Value is of type error is formatted as a string, by calling its Error method. Only errors in Attrs receive this special treatment, not errors embedded in structs, slices, maps or other data structures that are processed by the encoding/json package.

        Second, an encoding failure does not cause Handle to return an error. Instead, the error message is formatted as a string.

        Each call to Handle results in a single serialized call to io.Writer.Write.

        func (*JSONHandler) WithAttrs

        func (h *JSONHandler) WithAttrs(attrs []Attr) Handler

        WithAttrs returns a new JSONHandler whose attributes consists of h's attributes followed by attrs.

        func (*JSONHandler) WithGroup

        func (h *JSONHandler) WithGroup(name string) Handler

        type Kind

        Kind is the kind of a Value.

        type Kind int
        const (
            KindAny Kind = iota
            KindBool
            KindDuration
            KindFloat64
            KindInt64
            KindString
            KindTime
            KindUint64
            KindGroup
            KindLogValuer
        )

        func (Kind) String

        func (k Kind) String() string

        type Level

        A Level is the importance or severity of a log event. The higher the level, the more important or severe the event.

        type Level int

        Names for common levels.

        Level numbers are inherently arbitrary, but we picked them to satisfy three constraints. Any system can map them to another numbering scheme if it wishes.

        First, we wanted the default level to be Info, Since Levels are ints, Info is the default value for int, zero.

        Second, we wanted to make it easy to use levels to specify logger verbosity. Since a larger level means a more severe event, a logger that accepts events with smaller (or more negative) level means a more verbose logger. Logger verbosity is thus the negation of event severity, and the default verbosity of 0 accepts all events at least as severe as INFO.

        Third, we wanted some room between levels to accommodate schemes with named levels between ours. For example, Google Cloud Logging defines a Notice level between Info and Warn. Since there are only a few of these intermediate levels, the gap between the numbers need not be large. Our gap of 4 matches OpenTelemetry's mapping. Subtracting 9 from an OpenTelemetry level in the DEBUG, INFO, WARN and ERROR ranges converts it to the corresponding slog Level range. OpenTelemetry also has the names TRACE and FATAL, which slog does not. But those OpenTelemetry levels can still be represented as slog Levels by using the appropriate integers.

        const (
            LevelDebug Level = -4
            LevelInfo  Level = 0
            LevelWarn  Level = 4
            LevelError Level = 8
        )

        func SetLogLoggerLevel

        func SetLogLoggerLevel(level Level) (oldLevel Level)

        SetLogLoggerLevel controls the level for the bridge to the log package.

        Before SetDefault is called, slog top-level logging functions call the default log.Logger. In that mode, SetLogLoggerLevel sets the minimum level for those calls. By default, the minimum level is Info, so calls to Debug (as well as top-level logging calls at lower levels) will not be passed to the log.Logger. After calling

        slog.SetLogLoggerLevel(slog.LevelDebug)
        

        calls to Debug will be passed to the log.Logger.

        After SetDefault is called, calls to the default log.Logger are passed to the slog default handler. In that mode, SetLogLoggerLevel sets the level at which those calls are logged. That is, after calling

        slog.SetLogLoggerLevel(slog.LevelDebug)
        

        A call to log.Printf will result in output at level LevelDebug.

        SetLogLoggerLevel returns the previous value.

        Example (Log)

        This example shows how to use slog.SetLogLoggerLevel to change the minimal level of the internal default handler for slog package before calling slog.SetDefault.

        Code:

        defer log.SetFlags(log.Flags()) // revert changes after the example
        log.SetFlags(0)
        defer log.SetOutput(log.Writer()) // revert changes after the example
        log.SetOutput(os.Stdout)
        
        // Default logging level is slog.LevelInfo.
        log.Print("log debug") // log debug
        slog.Debug("debug")    // no output
        slog.Info("info")      // INFO info
        
        // Set the default logging level to slog.LevelDebug.
        currentLogLevel := slog.SetLogLoggerLevel(slog.LevelDebug)
        defer slog.SetLogLoggerLevel(currentLogLevel) // revert changes after the example
        
        log.Print("log debug") // log debug
        slog.Debug("debug")    // DEBUG debug
        slog.Info("info")      // INFO info
        
        

        Output:

        log debug
        INFO info
        log debug
        DEBUG debug
        INFO info
        

        Example (Slog)

        This example shows how to use slog.SetLogLoggerLevel to change the minimal level of the internal writer that uses the custom handler for log package after calling slog.SetDefault.

        Code:

        // Set the default logging level to slog.LevelError.
        currentLogLevel := slog.SetLogLoggerLevel(slog.LevelError)
        defer slog.SetLogLoggerLevel(currentLogLevel) // revert changes after the example
        
        defer slog.SetDefault(slog.Default()) // revert changes after the example
        slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime})))
        
        log.Print("error") // level=ERROR msg=error
        
        

        Output:

        level=ERROR msg=error
        

        func (Level) Level

        func (l Level) Level() Level

        Level returns the receiver. It implements Leveler.

        func (Level) MarshalJSON

        func (l Level) MarshalJSON() ([]byte, error)

        MarshalJSON implements encoding/json.Marshaler by quoting the output of Level.String.

        func (Level) MarshalText

        func (l Level) MarshalText() ([]byte, error)

        MarshalText implements encoding.TextMarshaler by calling Level.String.

        func (Level) String

        func (l Level) String() string

        String returns a name for the level. If the level has a name, then that name in uppercase is returned. If the level is between named values, then an integer is appended to the uppercased name. Examples:

        LevelWarn.String() => "WARN"
        (LevelInfo+2).String() => "INFO+2"
        

        func (*Level) UnmarshalJSON

        func (l *Level) UnmarshalJSON(data []byte) error

        UnmarshalJSON implements encoding/json.Unmarshaler It accepts any string produced by Level.MarshalJSON, ignoring case. It also accepts numeric offsets that would result in a different string on output. For example, "Error-8" would marshal as "INFO".

        func (*Level) UnmarshalText

        func (l *Level) UnmarshalText(data []byte) error

        UnmarshalText implements encoding.TextUnmarshaler. It accepts any string produced by Level.MarshalText, ignoring case. It also accepts numeric offsets that would result in a different string on output. For example, "Error-8" would marshal as "INFO".

        type LevelVar

        A LevelVar is a Level variable, to allow a Handler level to change dynamically. It implements Leveler as well as a Set method, and it is safe for use by multiple goroutines. The zero LevelVar corresponds to LevelInfo.

        type LevelVar struct {
            // contains filtered or unexported fields
        }
        

        func (*LevelVar) Level

        func (v *LevelVar) Level() Level

        Level returns v's level.

        func (*LevelVar) MarshalText

        func (v *LevelVar) MarshalText() ([]byte, error)

        MarshalText implements encoding.TextMarshaler by calling Level.MarshalText.

        func (*LevelVar) Set

        func (v *LevelVar) Set(l Level)

        Set sets v's level to l.

        func (*LevelVar) String

        func (v *LevelVar) String() string

        func (*LevelVar) UnmarshalText

        func (v *LevelVar) UnmarshalText(data []byte) error

        UnmarshalText implements encoding.TextUnmarshaler by calling Level.UnmarshalText.

        type Leveler

        A Leveler provides a Level value.

        As Level itself implements Leveler, clients typically supply a Level value wherever a Leveler is needed, such as in HandlerOptions. Clients who need to vary the level dynamically can provide a more complex Leveler implementation such as *LevelVar.

        type Leveler interface {
            Level() Level
        }

        type LogValuer

        A LogValuer is any Go value that can convert itself into a Value for logging.

        This mechanism may be used to defer expensive operations until they are needed, or to expand a single value into a sequence of components.

        type LogValuer interface {
            LogValue() Value
        }

        Example (Group)

        Code:

        package slog_test
        
        import "log/slog"
        
        type Name struct {
            First, Last string
        }
        
        // LogValue implements slog.LogValuer.
        // It returns a group containing the fields of
        // the Name, so that they appear together in the log output.
        func (n Name) LogValue() slog.Value {
            return slog.GroupValue(
                slog.String("first", n.First),
                slog.String("last", n.Last))
        }
        
        func ExampleLogValuer_group() {
            n := Name{"Perry", "Platypus"}
            slog.Info("mission accomplished", "agent", n)
        
            // JSON Output would look in part like:
            // {
            //     ...
            //     "msg": "mission accomplished",
            //     "agent": {
            //         "first": "Perry",
            //         "last": "Platypus"
            //     }
            // }
        }
        

        Example (Secret)

        This example demonstrates a Value that replaces itself with an alternative representation to avoid revealing secrets.

        Code:

        package slog_test
        
        import (
            "log/slog"
            "log/slog/internal/slogtest"
            "os"
        )
        
        // A token is a secret value that grants permissions.
        type Token string
        
        // LogValue implements slog.LogValuer.
        // It avoids revealing the token.
        func (Token) LogValue() slog.Value {
            return slog.StringValue("REDACTED_TOKEN")
        }
        
        // This example demonstrates a Value that replaces itself
        // with an alternative representation to avoid revealing secrets.
        func ExampleLogValuer_secret() {
            t := Token("shhhh!")
            logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}))
            logger.Info("permission granted", "user", "Perry", "token", t)
        
            // Output:
            // level=INFO msg="permission granted" user=Perry token=REDACTED_TOKEN
        }
        

        type Logger

        A Logger records structured information about each call to its Log, Debug, Info, Warn, and Error methods. For each call, it creates a Record and passes it to a Handler.

        To create a new Logger, call New or a Logger method that begins "With".

        type Logger struct {
            // contains filtered or unexported fields
        }
        

        func Default

        func Default() *Logger

        Default returns the default Logger.

        func New

        func New(h Handler) *Logger

        New creates a new Logger with the given non-nil Handler.

        func With

        func With(args ...any) *Logger

        With calls Logger.With on the default logger.

        func (*Logger) Debug

        func (l *Logger) Debug(msg string, args ...any)

        Debug logs at LevelDebug.

        func (*Logger) DebugContext

        func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any)

        DebugContext logs at LevelDebug with the given context.

        func (*Logger) Enabled

        func (l *Logger) Enabled(ctx context.Context, level Level) bool

        Enabled reports whether l emits log records at the given context and level.

        func (*Logger) Error

        func (l *Logger) Error(msg string, args ...any)

        Error logs at LevelError.

        func (*Logger) ErrorContext

        func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any)

        ErrorContext logs at LevelError with the given context.

        func (*Logger) Handler

        func (l *Logger) Handler() Handler

        Handler returns l's Handler.

        func (*Logger) Info

        func (l *Logger) Info(msg string, args ...any)

        Info logs at LevelInfo.

        func (*Logger) InfoContext

        func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any)

        InfoContext logs at LevelInfo with the given context.

        func (*Logger) Log

        func (l *Logger) Log(ctx context.Context, level Level, msg string, args ...any)

        Log emits a log record with the current time and the given level and message. The Record's Attrs consist of the Logger's attributes followed by the Attrs specified by args.

        The attribute arguments are processed as follows:

        • If an argument is an Attr, it is used as is.
        • If an argument is a string and this is not the last argument, the following argument is treated as the value and the two are combined into an Attr.
        • Otherwise, the argument is treated as a value with key "!BADKEY".

        func (*Logger) LogAttrs

        func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)

        LogAttrs is a more efficient version of Logger.Log that accepts only Attrs.

        func (*Logger) Warn

        func (l *Logger) Warn(msg string, args ...any)

        Warn logs at LevelWarn.

        func (*Logger) WarnContext

        func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any)

        WarnContext logs at LevelWarn with the given context.

        func (*Logger) With

        func (l *Logger) With(args ...any) *Logger

        With returns a Logger that includes the given attributes in each output operation. Arguments are converted to attributes as if by Logger.Log.

        func (*Logger) WithGroup

        func (l *Logger) WithGroup(name string) *Logger

        WithGroup returns a Logger that starts a group, if name is non-empty. The keys of all attributes added to the Logger will be qualified by the given name. (How that qualification happens depends on the [Handler.WithGroup] method of the Logger's Handler.)

        If name is empty, WithGroup returns the receiver.

        type Record

        A Record holds information about a log event. Copies of a Record share state. Do not modify a Record after handing out a copy to it. Call NewRecord to create a new Record. Use Record.Clone to create a copy with no shared state.

        type Record struct {
            // The time at which the output method (Log, Info, etc.) was called.
            Time time.Time
        
            // The log message.
            Message string
        
            // The level of the event.
            Level Level
        
            // The program counter at the time the record was constructed, as determined
            // by runtime.Callers. If zero, no program counter is available.
            //
            // The only valid use for this value is as an argument to
            // [runtime.CallersFrames]. In particular, it must not be passed to
            // [runtime.FuncForPC].
            PC uintptr
            // contains filtered or unexported fields
        }
        

        func NewRecord

        func NewRecord(t time.Time, level Level, msg string, pc uintptr) Record

        NewRecord creates a Record from the given arguments. Use Record.AddAttrs to add attributes to the Record.

        NewRecord is intended for logging APIs that want to support a Handler as a backend.

        func (*Record) Add

        func (r *Record) Add(args ...any)

        Add converts the args to Attrs as described in Logger.Log, then appends the Attrs to the Record's list of Attrs. It omits empty groups.

        func (*Record) AddAttrs

        func (r *Record) AddAttrs(attrs ...Attr)

        AddAttrs appends the given Attrs to the Record's list of Attrs. It omits empty groups.

        func (Record) Attrs

        func (r Record) Attrs(f func(Attr) bool)

        Attrs calls f on each Attr in the Record. Iteration stops if f returns false.

        func (Record) Clone

        func (r Record) Clone() Record

        Clone returns a copy of the record with no shared state. The original record and the clone can both be modified without interfering with each other.

        func (Record) NumAttrs

        func (r Record) NumAttrs() int

        NumAttrs returns the number of attributes in the Record.

        type Source

        Source describes the location of a line of source code.

        type Source struct {
            // Function is the package path-qualified function name containing the
            // source line. If non-empty, this string uniquely identifies a single
            // function in the program. This may be the empty string if not known.
            Function string `json:"function"`
            // File and Line are the file name and line number (1-based) of the source
            // line. These may be the empty string and zero, respectively, if not known.
            File string `json:"file"`
            Line int    `json:"line"`
        }
        

        type TextHandler

        TextHandler is a Handler that writes Records to an io.Writer as a sequence of key=value pairs separated by spaces and followed by a newline.

        type TextHandler struct {
            // contains filtered or unexported fields
        }
        

        func NewTextHandler

        func NewTextHandler(w io.Writer, opts *HandlerOptions) *TextHandler

        NewTextHandler creates a TextHandler that writes to w, using the given options. If opts is nil, the default options are used.

        func (*TextHandler) Enabled

        func (h *TextHandler) Enabled(_ context.Context, level Level) bool

        Enabled reports whether the handler handles records at the given level. The handler ignores records whose level is lower.

        func (*TextHandler) Handle

        func (h *TextHandler) Handle(_ context.Context, r Record) error

        Handle formats its argument Record as a single line of space-separated key=value items.

        If the Record's time is zero, the time is omitted. Otherwise, the key is "time" and the value is output in RFC3339 format with millisecond precision.

        If the Record's level is zero, the level is omitted. Otherwise, the key is "level" and the value of Level.String is output.

        If the AddSource option is set and source information is available, the key is "source" and the value is output as FILE:LINE.

        The message's key is "msg".

        To modify these or other attributes, or remove them from the output, use [HandlerOptions.ReplaceAttr].

        If a value implements encoding.TextMarshaler, the result of MarshalText is written. Otherwise, the result of fmt.Sprint is written.

        Keys and values are quoted with strconv.Quote if they contain Unicode space characters, non-printing characters, '"' or '='.

        Keys inside groups consist of components (keys or group names) separated by dots. No further escaping is performed. Thus there is no way to determine from the key "a.b.c" whether there are two groups "a" and "b" and a key "c", or a single group "a.b" and a key "c", or single group "a" and a key "b.c". If it is necessary to reconstruct the group structure of a key even in the presence of dots inside components, use [HandlerOptions.ReplaceAttr] to encode that information in the key.

        Each call to Handle results in a single serialized call to io.Writer.Write.

        func (*TextHandler) WithAttrs

        func (h *TextHandler) WithAttrs(attrs []Attr) Handler

        WithAttrs returns a new TextHandler whose attributes consists of h's attributes followed by attrs.

        func (*TextHandler) WithGroup

        func (h *TextHandler) WithGroup(name string) Handler

        type Value

        A Value can represent any Go value, but unlike type any, it can represent most small values without an allocation. The zero Value corresponds to nil.

        type Value struct {
            // contains filtered or unexported fields
        }
        

        func AnyValue

        func AnyValue(v any) Value

        AnyValue returns a Value for the supplied value.

        If the supplied value is of type Value, it is returned unmodified.

        Given a value of one of Go's predeclared string, bool, or (non-complex) numeric types, AnyValue returns a Value of kind KindString, KindBool, KindUint64, KindInt64, or KindFloat64. The width of the original numeric type is not preserved.

        Given a time.Time or time.Duration value, AnyValue returns a Value of kind KindTime or KindDuration. The monotonic time is not preserved.

        For nil, or values of all other types, including named types whose underlying type is numeric, AnyValue returns a value of kind KindAny.

        func BoolValue

        func BoolValue(v bool) Value

        BoolValue returns a Value for a bool.

        func DurationValue

        func DurationValue(v time.Duration) Value

        DurationValue returns a Value for a time.Duration.

        func Float64Value

        func Float64Value(v float64) Value

        Float64Value returns a Value for a floating-point number.

        func GroupValue

        func GroupValue(as ...Attr) Value

        GroupValue returns a new Value for a list of Attrs. The caller must not subsequently mutate the argument slice.

        func Int64Value

        func Int64Value(v int64) Value

        Int64Value returns a Value for an int64.

        func IntValue

        func IntValue(v int) Value

        IntValue returns a Value for an int.

        func StringValue

        func StringValue(value string) Value

        StringValue returns a new Value for a string.

        func TimeValue

        func TimeValue(v time.Time) Value

        TimeValue returns a Value for a time.Time. It discards the monotonic portion.

        func Uint64Value

        func Uint64Value(v uint64) Value

        Uint64Value returns a Value for a uint64.

        func (Value) Any

        func (v Value) Any() any

        Any returns v's value as an any.

        func (Value) Bool

        func (v Value) Bool() bool

        Bool returns v's value as a bool. It panics if v is not a bool.

        func (Value) Duration

        func (v Value) Duration() time.Duration

        Duration returns v's value as a time.Duration. It panics if v is not a time.Duration.

        func (Value) Equal

        func (v Value) Equal(w Value) bool

        Equal reports whether v and w represent the same Go value.

        func (Value) Float64

        func (v Value) Float64() float64

        Float64 returns v's value as a float64. It panics if v is not a float64.

        func (Value) Group

        func (v Value) Group() []Attr

        Group returns v's value as a []Attr. It panics if v's Kind is not KindGroup.

        func (Value) Int64

        func (v Value) Int64() int64

        Int64 returns v's value as an int64. It panics if v is not a signed integer.

        func (Value) Kind

        func (v Value) Kind() Kind

        Kind returns v's Kind.

        func (Value) LogValuer

        func (v Value) LogValuer() LogValuer

        LogValuer returns v's value as a LogValuer. It panics if v is not a LogValuer.

        func (Value) Resolve

        func (v Value) Resolve() (rv Value)

        Resolve repeatedly calls LogValue on v while it implements LogValuer, and returns the result. If v resolves to a group, the group's attributes' values are not recursively resolved. If the number of LogValue calls exceeds a threshold, a Value containing an error is returned. Resolve's return value is guaranteed not to be of Kind KindLogValuer.

        func (Value) String

        func (v Value) String() string

        String returns Value's value as a string, formatted like fmt.Sprint. Unlike the methods Int64, Float64, and so on, which panic if v is of the wrong kind, String never panics.

        func (Value) Time

        func (v Value) Time() time.Time

        Time returns v's value as a time.Time. It panics if v is not a time.Time.

        func (Value) Uint64

        func (v Value) Uint64() uint64

        Uint64 returns v's value as a uint64. It panics if v is not an unsigned integer.

        Subdirectories

        Name Synopsis
        ..
        syslog - Go Documentation Server
        ...

        Package syslog

        import "log/syslog"
        Overview
        Index
        Examples

        Overview ▾

        Package syslog provides a simple interface to the system log service. It can send messages to the syslog daemon using UNIX domain sockets, UDP or TCP.

        Only one call to Dial is necessary. On write failures, the syslog client will attempt to reconnect to the server and write again.

        The syslog package is frozen and is not accepting new features. Some external packages provide more functionality. See:

        https://godoc.org/?q=syslog
        

        func NewLogger

        func NewLogger(p Priority, logFlag int) (*log.Logger, error)

        NewLogger creates a log.Logger whose output is written to the system log service with the specified priority, a combination of the syslog facility and severity. The logFlag argument is the flag set passed through to log.New to create the Logger.

        type Priority

        The Priority is a combination of the syslog facility and severity. For example, LOG_ALERT | LOG_FTP sends an alert severity message from the FTP facility. The default severity is LOG_EMERG; the default facility is LOG_KERN.

        type Priority int
        const (
        
            // From /usr/include/sys/syslog.h.
            // These are the same on Linux, BSD, and OS X.
            LOG_EMERG Priority = iota
            LOG_ALERT
            LOG_CRIT
            LOG_ERR
            LOG_WARNING
            LOG_NOTICE
            LOG_INFO
            LOG_DEBUG
        )
        const (
        
            // From /usr/include/sys/syslog.h.
            // These are the same up to LOG_FTP on Linux, BSD, and OS X.
            LOG_KERN Priority = iota << 3
            LOG_USER
            LOG_MAIL
            LOG_DAEMON
            LOG_AUTH
            LOG_SYSLOG
            LOG_LPR
            LOG_NEWS
            LOG_UUCP
            LOG_CRON
            LOG_AUTHPRIV
            LOG_FTP
        
            LOG_LOCAL0
            LOG_LOCAL1
            LOG_LOCAL2
            LOG_LOCAL3
            LOG_LOCAL4
            LOG_LOCAL5
            LOG_LOCAL6
            LOG_LOCAL7
        )

        type Writer

        A Writer is a connection to a syslog server.

        type Writer struct {
            // contains filtered or unexported fields
        }
        

        func Dial

        func Dial(network, raddr string, priority Priority, tag string) (*Writer, error)

        Dial establishes a connection to a log daemon by connecting to address raddr on the specified network. Each write to the returned writer sends a log message with the facility and severity (from priority) and tag. If tag is empty, the os.Args[0] is used. If network is empty, Dial will connect to the local syslog server. Otherwise, see the documentation for net.Dial for valid values of network and raddr.

        Example

        Code:

        sysLog, err := syslog.Dial("tcp", "localhost:1234",
            syslog.LOG_WARNING|syslog.LOG_DAEMON, "demotag")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Fprintf(sysLog, "This is a daemon warning with demotag.")
        sysLog.Emerg("And this is a daemon emergency with demotag.")
        

        func New

        func New(priority Priority, tag string) (*Writer, error)

        New establishes a new connection to the system log daemon. Each write to the returned writer sends a log message with the given priority (a combination of the syslog facility and severity) and prefix tag. If tag is empty, the os.Args[0] is used.

        func (*Writer) Alert

        func (w *Writer) Alert(m string) error

        Alert logs a message with severity LOG_ALERT, ignoring the severity passed to New.

        func (*Writer) Close

        func (w *Writer) Close() error

        Close closes a connection to the syslog daemon.

        func (*Writer) Crit

        func (w *Writer) Crit(m string) error

        Crit logs a message with severity LOG_CRIT, ignoring the severity passed to New.

        func (*Writer) Debug

        func (w *Writer) Debug(m string) error

        Debug logs a message with severity LOG_DEBUG, ignoring the severity passed to New.

        func (*Writer) Emerg

        func (w *Writer) Emerg(m string) error

        Emerg logs a message with severity LOG_EMERG, ignoring the severity passed to New.

        func (*Writer) Err

        func (w *Writer) Err(m string) error

        Err logs a message with severity LOG_ERR, ignoring the severity passed to New.

        func (*Writer) Info

        func (w *Writer) Info(m string) error

        Info logs a message with severity LOG_INFO, ignoring the severity passed to New.

        func (*Writer) Notice

        func (w *Writer) Notice(m string) error

        Notice logs a message with severity LOG_NOTICE, ignoring the severity passed to New.

        func (*Writer) Warning

        func (w *Writer) Warning(m string) error

        Warning logs a message with severity LOG_WARNING, ignoring the severity passed to New.

        func (*Writer) Write

        func (w *Writer) Write(b []byte) (int, error)

        Write sends a log message to the syslog daemon.

        Bugs

        • This package is not implemented on Windows. As the syslog package is frozen, Windows users are encouraged to use a package outside of the standard library. For background, see https://golang.org/issue/1108.

        • This package is not implemented on Plan 9.

        maps - Go Documentation Server
        ...

        Package maps

        import "maps"
        Overview
        Index
        Examples

        Overview ▾

        Package maps defines various functions useful with maps of any type.

        func Clone

        func Clone[M ~map[K]V, K comparable, V any](m M) M

        Clone returns a copy of m. This is a shallow clone: the new keys and values are set using ordinary assignment.

        Example

        Code:

        m1 := map[string]int{
            "key": 1,
        }
        m2 := maps.Clone(m1)
        m2["key"] = 100
        fmt.Println(m1["key"])
        fmt.Println(m2["key"])
        
        m3 := map[string][]int{
            "key": {1, 2, 3},
        }
        m4 := maps.Clone(m3)
        fmt.Println(m4["key"][0])
        m4["key"][0] = 100
        fmt.Println(m3["key"][0])
        fmt.Println(m4["key"][0])
        
        

        Output:

        1
        100
        1
        100
        100
        

        func Copy

        func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2)

        Copy copies all key/value pairs in src adding them to dst. When a key in src is already present in dst, the value in dst will be overwritten by the value associated with the key in src.

        Example

        Code:

        m1 := map[string]int{
            "one": 1,
            "two": 2,
        }
        m2 := map[string]int{
            "one": 10,
        }
        
        maps.Copy(m2, m1)
        fmt.Println("m2 is:", m2)
        
        m2["one"] = 100
        fmt.Println("m1 is:", m1)
        fmt.Println("m2 is:", m2)
        
        m3 := map[string][]int{
            "one": {1, 2, 3},
            "two": {4, 5, 6},
        }
        m4 := map[string][]int{
            "one": {7, 8, 9},
        }
        
        maps.Copy(m4, m3)
        fmt.Println("m4 is:", m4)
        
        m4["one"][0] = 100
        fmt.Println("m3 is:", m3)
        fmt.Println("m4 is:", m4)
        
        

        Output:

        m2 is: map[one:1 two:2]
        m1 is: map[one:1 two:2]
        m2 is: map[one:100 two:2]
        m4 is: map[one:[1 2 3] two:[4 5 6]]
        m3 is: map[one:[100 2 3] two:[4 5 6]]
        m4 is: map[one:[100 2 3] two:[4 5 6]]
        

        func DeleteFunc

        func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool)

        DeleteFunc deletes any key/value pairs from m for which del returns true.

        Example

        Code:

        m := map[string]int{
            "one":   1,
            "two":   2,
            "three": 3,
            "four":  4,
        }
        maps.DeleteFunc(m, func(k string, v int) bool {
            return v%2 != 0 // delete odd values
        })
        fmt.Println(m)
        

        Output:

        map[four:4 two:2]
        

        func Equal

        func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool

        Equal reports whether two maps contain the same key/value pairs. Values are compared using ==.

        Example

        Code:

        m1 := map[int]string{
            1:    "one",
            10:   "Ten",
            1000: "THOUSAND",
        }
        m2 := map[int]string{
            1:    "one",
            10:   "Ten",
            1000: "THOUSAND",
        }
        m3 := map[int]string{
            1:    "one",
            10:   "ten",
            1000: "thousand",
        }
        
        fmt.Println(maps.Equal(m1, m2))
        fmt.Println(maps.Equal(m1, m3))
        

        Output:

        true
        false
        

        func EqualFunc

        func EqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](m1 M1, m2 M2, eq func(V1, V2) bool) bool

        EqualFunc is like Equal, but compares values using eq. Keys are still compared with ==.

        Example

        Code:

        m1 := map[int]string{
            1:    "one",
            10:   "Ten",
            1000: "THOUSAND",
        }
        m2 := map[int][]byte{
            1:    []byte("One"),
            10:   []byte("Ten"),
            1000: []byte("Thousand"),
        }
        eq := maps.EqualFunc(m1, m2, func(v1 string, v2 []byte) bool {
            return strings.ToLower(v1) == strings.ToLower(string(v2))
        })
        fmt.Println(eq)
        

        Output:

        true
        
        math - Go Documentation Server
        ...

        Package math

        Overview ▾

        Package math provides basic constants and mathematical functions.

        This package does not guarantee bit-identical results across architectures.

        Index ▾

        Constants
        func Abs(x float64) float64
        func Acos(x float64) float64
        func Acosh(x float64) float64
        func Asin(x float64) float64
        func Asinh(x float64) float64
        func Atan(x float64) float64
        func Atan2(y, x float64) float64
        func Atanh(x float64) float64
        func Cbrt(x float64) float64
        func Ceil(x float64) float64
        func Copysign(f, sign float64) float64
        func Cos(x float64) float64
        func Cosh(x float64) float64
        func Dim(x, y float64) float64
        func Erf(x float64) float64
        func Erfc(x float64) float64
        func Erfcinv(x float64) float64
        func Erfinv(x float64) float64
        func Exp(x float64) float64
        func Exp2(x float64) float64
        func Expm1(x float64) float64
        func FMA(x, y, z float64) float64
        func Float32bits(f float32) uint32
        func Float32frombits(b uint32) float32
        func Float64bits(f float64) uint64
        func Float64frombits(b uint64) float64
        func Floor(x float64) float64
        func Frexp(f float64) (frac float64, exp int)
        func Gamma(x float64) float64
        func Hypot(p, q float64) float64
        func Ilogb(x float64) int
        func Inf(sign int) float64
        func IsInf(f float64, sign int) bool
        func IsNaN(f float64) (is bool)
        func J0(x float64) float64
        func J1(x float64) float64
        func Jn(n int, x float64) float64
        func Ldexp(frac float64, exp int) float64
        func Lgamma(x float64) (lgamma float64, sign int)
        func Log(x float64) float64
        func Log10(x float64) float64
        func Log1p(x float64) float64
        func Log2(x float64) float64
        func Logb(x float64) float64
        func Max(x, y float64) float64
        func Min(x, y float64) float64
        func Mod(x, y float64) float64
        func Modf(f float64) (int float64, frac float64)
        func NaN() float64
        func Nextafter(x, y float64) (r float64)
        func Nextafter32(x, y float32) (r float32)
        func Pow(x, y float64) float64
        func Pow10(n int) float64
        func Remainder(x, y float64) float64
        func Round(x float64) float64
        func RoundToEven(x float64) float64
        func Signbit(x float64) bool
        func Sin(x float64) float64
        func Sincos(x float64) (sin, cos float64)
        func Sinh(x float64) float64
        func Sqrt(x float64) float64
        func Tan(x float64) float64
        func Tanh(x float64) float64
        func Trunc(x float64) float64
        func Y0(x float64) float64
        func Y1(x float64) float64
        func Yn(n int, x float64) float64

        Package files

        abs.go acosh.go asin.go asinh.go atan.go atan2.go atanh.go bits.go cbrt.go const.go copysign.go dim.go dim_asm.go erf.go erfinv.go exp.go exp2_noasm.go exp_amd64.go exp_asm.go expm1.go floor.go floor_asm.go fma.go frexp.go gamma.go hypot.go hypot_asm.go j0.go j1.go jn.go ldexp.go lgamma.go log.go log10.go log1p.go log_asm.go logb.go mod.go modf.go modf_noasm.go nextafter.go pow.go pow10.go remainder.go signbit.go sin.go sincos.go sinh.go sqrt.go stubs.go tan.go tanh.go trig_reduce.go unsafe.go

        Constants

        Mathematical constants.

        const (
            E   = 2.71828182845904523536028747135266249775724709369995957496696763 // https://oeis.org/A001113
            Pi  = 3.14159265358979323846264338327950288419716939937510582097494459 // https://oeis.org/A000796
            Phi = 1.61803398874989484820458683436563811772030917980576286213544862 // https://oeis.org/A001622
        
            Sqrt2   = 1.41421356237309504880168872420969807856967187537694807317667974 // https://oeis.org/A002193
            SqrtE   = 1.64872127070012814684865078781416357165377610071014801157507931 // https://oeis.org/A019774
            SqrtPi  = 1.77245385090551602729816748334114518279754945612238712821380779 // https://oeis.org/A002161
            SqrtPhi = 1.27201964951406896425242246173749149171560804184009624861664038 // https://oeis.org/A139339
        
            Ln2    = 0.693147180559945309417232121458176568075500134360255254120680009 // https://oeis.org/A002162
            Log2E  = 1 / Ln2
            Ln10   = 2.30258509299404568401799145468436420760110148862877297603332790 // https://oeis.org/A002392
            Log10E = 1 / Ln10
        )

        Floating-point limit values. Max is the largest finite value representable by the type. SmallestNonzero is the smallest positive, non-zero value representable by the type.

        const (
            MaxFloat32             = 0x1p127 * (1 + (1 - 0x1p-23)) // 3.40282346638528859811704183484516925440e+38
            SmallestNonzeroFloat32 = 0x1p-126 * 0x1p-23            // 1.401298464324817070923729583289916131280e-45
        
            MaxFloat64             = 0x1p1023 * (1 + (1 - 0x1p-52)) // 1.79769313486231570814527423731704356798070e+308
            SmallestNonzeroFloat64 = 0x1p-1022 * 0x1p-52            // 4.9406564584124654417656879286822137236505980e-324
        )

        Integer limit values.

        const (
            MaxInt    = 1<<(intSize-1) - 1  // MaxInt32 or MaxInt64 depending on intSize.
            MinInt    = -1 << (intSize - 1) // MinInt32 or MinInt64 depending on intSize.
            MaxInt8   = 1<<7 - 1            // 127
            MinInt8   = -1 << 7             // -128
            MaxInt16  = 1<<15 - 1           // 32767
            MinInt16  = -1 << 15            // -32768
            MaxInt32  = 1<<31 - 1           // 2147483647
            MinInt32  = -1 << 31            // -2147483648
            MaxInt64  = 1<<63 - 1           // 9223372036854775807
            MinInt64  = -1 << 63            // -9223372036854775808
            MaxUint   = 1<<intSize - 1      // MaxUint32 or MaxUint64 depending on intSize.
            MaxUint8  = 1<<8 - 1            // 255
            MaxUint16 = 1<<16 - 1           // 65535
            MaxUint32 = 1<<32 - 1           // 4294967295
            MaxUint64 = 1<<64 - 1           // 18446744073709551615
        )

        func Abs

        func Abs(x float64) float64

        Abs returns the absolute value of x.

        Special cases are:

        Abs(±Inf) = +Inf
        Abs(NaN) = NaN
        

        Example

        Code:

        x := math.Abs(-2)
        fmt.Printf("%.1f\n", x)
        
        y := math.Abs(2)
        fmt.Printf("%.1f\n", y)
        

        Output:

        2.0
        2.0
        

        func Acos

        func Acos(x float64) float64

        Acos returns the arccosine, in radians, of x.

        Special case is:

        Acos(x) = NaN if x < -1 or x > 1
        

        Example

        Code:

        fmt.Printf("%.2f", math.Acos(1))
        

        Output:

        0.00
        

        func Acosh

        func Acosh(x float64) float64

        Acosh returns the inverse hyperbolic cosine of x.

        Special cases are:

        Acosh(+Inf) = +Inf
        Acosh(x) = NaN if x < 1
        Acosh(NaN) = NaN
        

        Example

        Code:

        fmt.Printf("%.2f", math.Acosh(1))
        

        Output:

        0.00
        

        func Asin

        func Asin(x float64) float64

        Asin returns the arcsine, in radians, of x.

        Special cases are:

        Asin(±0) = ±0
        Asin(x) = NaN if x < -1 or x > 1
        

        Example

        Code:

        fmt.Printf("%.2f", math.Asin(0))
        

        Output:

        0.00
        

        func Asinh

        func Asinh(x float64) float64

        Asinh returns the inverse hyperbolic sine of x.

        Special cases are:

        Asinh(±0) = ±0
        Asinh(±Inf) = ±Inf
        Asinh(NaN) = NaN
        

        Example

        Code:

        fmt.Printf("%.2f", math.Asinh(0))
        

        Output:

        0.00
        

        func Atan

        func Atan(x float64) float64

        Atan returns the arctangent, in radians, of x.

        Special cases are:

        Atan(±0) = ±0
        Atan(±Inf) = ±Pi/2
        

        Example

        Code:

        fmt.Printf("%.2f", math.Atan(0))
        

        Output:

        0.00
        

        func Atan2

        func Atan2(y, x float64) float64

        Atan2 returns the arc tangent of y/x, using the signs of the two to determine the quadrant of the return value.

        Special cases are (in order):

        Atan2(y, NaN) = NaN
        Atan2(NaN, x) = NaN
        Atan2(+0, x>=0) = +0
        Atan2(-0, x>=0) = -0
        Atan2(+0, x<=-0) = +Pi
        Atan2(-0, x<=-0) = -Pi
        Atan2(y>0, 0) = +Pi/2
        Atan2(y<0, 0) = -Pi/2
        Atan2(+Inf, +Inf) = +Pi/4
        Atan2(-Inf, +Inf) = -Pi/4
        Atan2(+Inf, -Inf) = 3Pi/4
        Atan2(-Inf, -Inf) = -3Pi/4
        Atan2(y, +Inf) = 0
        Atan2(y>0, -Inf) = +Pi
        Atan2(y<0, -Inf) = -Pi
        Atan2(+Inf, x) = +Pi/2
        Atan2(-Inf, x) = -Pi/2
        

        Example

        Code:

        fmt.Printf("%.2f", math.Atan2(0, 0))
        

        Output:

        0.00
        

        func Atanh

        func Atanh(x float64) float64

        Atanh returns the inverse hyperbolic tangent of x.

        Special cases are:

        Atanh(1) = +Inf
        Atanh(±0) = ±0
        Atanh(-1) = -Inf
        Atanh(x) = NaN if x < -1 or x > 1
        Atanh(NaN) = NaN
        

        Example

        Code:

        fmt.Printf("%.2f", math.Atanh(0))
        

        Output:

        0.00
        

        func Cbrt

        func Cbrt(x float64) float64

        Cbrt returns the cube root of x.

        Special cases are:

        Cbrt(±0) = ±0
        Cbrt(±Inf) = ±Inf
        Cbrt(NaN) = NaN
        

        Example

        Code:

        fmt.Printf("%.2f\n", math.Cbrt(8))
        fmt.Printf("%.2f\n", math.Cbrt(27))
        

        Output:

        2.00
        3.00
        

        func Ceil

        func Ceil(x float64) float64

        Ceil returns the least integer value greater than or equal to x.

        Special cases are:

        Ceil(±0) = ±0
        Ceil(±Inf) = ±Inf
        Ceil(NaN) = NaN
        

        Example

        Code:

        c := math.Ceil(1.49)
        fmt.Printf("%.1f", c)
        

        Output:

        2.0
        

        func Copysign

        func Copysign(f, sign float64) float64

        Copysign returns a value with the magnitude of f and the sign of sign.

        Example

        Code:

        fmt.Printf("%.2f", math.Copysign(3.2, -1))
        

        Output:

        -3.20
        

        func Cos

        func Cos(x float64) float64

        Cos returns the cosine of the radian argument x.

        Special cases are:

        Cos(±Inf) = NaN
        Cos(NaN) = NaN
        

        Example

        Code:

        fmt.Printf("%.2f", math.Cos(math.Pi/2))
        

        Output:

        0.00
        

        func Cosh

        func Cosh(x float64) float64

        Cosh returns the hyperbolic cosine of x.

        Special cases are:

        Cosh(±0) = 1
        Cosh(±Inf) = +Inf
        Cosh(NaN) = NaN
        

        Example

        Code:

        fmt.Printf("%.2f", math.Cosh(0))
        

        Output:

        1.00
        

        func Dim

        func Dim(x, y float64) float64

        Dim returns the maximum of x-y or 0.

        Special cases are:

        Dim(+Inf, +Inf) = NaN
        Dim(-Inf, -Inf) = NaN
        Dim(x, NaN) = Dim(NaN, x) = NaN
        

        Example

        Code:

        fmt.Printf("%.2f\n", math.Dim(4, -2))
        fmt.Printf("%.2f\n", math.Dim(-4, 2))
        

        Output:

        6.00
        0.00
        

        func Erf

        func Erf(x float64) float64

        Erf returns the error function of x.

        Special cases are:

        Erf(+Inf) = 1
        Erf(-Inf) = -1
        Erf(NaN) = NaN
        

        func Erfc

        func Erfc(x float64) float64

        Erfc returns the complementary error function of x.

        Special cases are:

        Erfc(+Inf) = 0
        Erfc(-Inf) = 2
        Erfc(NaN) = NaN
        

        func Erfcinv

        func Erfcinv(x float64) float64

        Erfcinv returns the inverse of Erfc(x).

        Special cases are:

        Erfcinv(0) = +Inf
        Erfcinv(2) = -Inf
        Erfcinv(x) = NaN if x < 0 or x > 2
        Erfcinv(NaN) = NaN
        

        func Erfinv

        func Erfinv(x float64) float64

        Erfinv returns the inverse error function of x.

        Special cases are:

        Erfinv(1) = +Inf
        Erfinv(-1) = -Inf
        Erfinv(x) = NaN if x < -1 or x > 1
        Erfinv(NaN) = NaN
        

        func Exp

        func Exp(x float64) float64

        Exp returns e**x, the base-e exponential of x.

        Special cases are:

        Exp(+Inf) = +Inf
        Exp(NaN) = NaN
        

        Very large values overflow to 0 or +Inf. Very small values underflow to 1.

        Example

        Code:

        fmt.Printf("%.2f\n", math.Exp(1))
        fmt.Printf("%.2f\n", math.Exp(2))
        fmt.Printf("%.2f\n", math.Exp(-1))
        

        Output:

        2.72
        7.39
        0.37
        

        func Exp2

        func Exp2(x float64) float64

        Exp2 returns 2**x, the base-2 exponential of x.

        Special cases are the same as Exp.

        Example

        Code:

        fmt.Printf("%.2f\n", math.Exp2(1))
        fmt.Printf("%.2f\n", math.Exp2(-3))
        

        Output:

        2.00
        0.12
        

        func Expm1

        func Expm1(x float64) float64

        Expm1 returns e**x - 1, the base-e exponential of x minus 1. It is more accurate than Exp(x) - 1 when x is near zero.

        Special cases are:

        Expm1(+Inf) = +Inf
        Expm1(-Inf) = -1
        Expm1(NaN) = NaN
        

        Very large values overflow to -1 or +Inf.

        Example

        Code:

        fmt.Printf("%.6f\n", math.Expm1(0.01))
        fmt.Printf("%.6f\n", math.Expm1(-1))
        

        Output:

        0.010050
        -0.632121
        

        func FMA

        func FMA(x, y, z float64) float64

        FMA returns x * y + z, computed with only one rounding. (That is, FMA returns the fused multiply-add of x, y, and z.)

        func Float32bits

        func Float32bits(f float32) uint32

        Float32bits returns the IEEE 754 binary representation of f, with the sign bit of f and the result in the same bit position. Float32bits(Float32frombits(x)) == x.

        func Float32frombits

        func Float32frombits(b uint32) float32

        Float32frombits returns the floating-point number corresponding to the IEEE 754 binary representation b, with the sign bit of b and the result in the same bit position. Float32frombits(Float32bits(x)) == x.

        func Float64bits

        func Float64bits(f float64) uint64

        Float64bits returns the IEEE 754 binary representation of f, with the sign bit of f and the result in the same bit position, and Float64bits(Float64frombits(x)) == x.

        func Float64frombits

        func Float64frombits(b uint64) float64

        Float64frombits returns the floating-point number corresponding to the IEEE 754 binary representation b, with the sign bit of b and the result in the same bit position. Float64frombits(Float64bits(x)) == x.

        func Floor

        func Floor(x float64) float64

        Floor returns the greatest integer value less than or equal to x.

        Special cases are:

        Floor(±0) = ±0
        Floor(±Inf) = ±Inf
        Floor(NaN) = NaN
        

        Example

        Code:

        c := math.Floor(1.51)
        fmt.Printf("%.1f", c)
        

        Output:

        1.0
        

        func Frexp

        func Frexp(f float64) (frac float64, exp int)

        Frexp breaks f into a normalized fraction and an integral power of two. It returns frac and exp satisfying f == frac × 2**exp, with the absolute value of frac in the interval [½, 1).

        Special cases are:

        Frexp(±0) = ±0, 0
        Frexp(±Inf) = ±Inf, 0
        Frexp(NaN) = NaN, 0
        

        func Gamma

        func Gamma(x float64) float64

        Gamma returns the Gamma function of x.

        Special cases are:

        Gamma(+Inf) = +Inf
        Gamma(+0) = +Inf
        Gamma(-0) = -Inf
        Gamma(x) = NaN for integer x < 0
        Gamma(-Inf) = NaN
        Gamma(NaN) = NaN
        

        func Hypot

        func Hypot(p, q float64) float64

        Hypot returns Sqrt(p*p + q*q), taking care to avoid unnecessary overflow and underflow.

        Special cases are:

        Hypot(±Inf, q) = +Inf
        Hypot(p, ±Inf) = +Inf
        Hypot(NaN, q) = NaN
        Hypot(p, NaN) = NaN
        

        func Ilogb

        func Ilogb(x float64) int

        Ilogb returns the binary exponent of x as an integer.

        Special cases are:

        Ilogb(±Inf) = MaxInt32
        Ilogb(0) = MinInt32
        Ilogb(NaN) = MaxInt32
        

        func Inf

        func Inf(sign int) float64

        Inf returns positive infinity if sign >= 0, negative infinity if sign < 0.

        func IsInf

        func IsInf(f float64, sign int) bool

        IsInf reports whether f is an infinity, according to sign. If sign > 0, IsInf reports whether f is positive infinity. If sign < 0, IsInf reports whether f is negative infinity. If sign == 0, IsInf reports whether f is either infinity.

        func IsNaN

        func IsNaN(f float64) (is bool)

        IsNaN reports whether f is an IEEE 754 “not-a-number” value.

        func J0

        func J0(x float64) float64

        J0 returns the order-zero Bessel function of the first kind.

        Special cases are:

        J0(±Inf) = 0
        J0(0) = 1
        J0(NaN) = NaN
        

        func J1

        func J1(x float64) float64

        J1 returns the order-one Bessel function of the first kind.

        Special cases are:

        J1(±Inf) = 0
        J1(NaN) = NaN
        

        func Jn

        func Jn(n int, x float64) float64

        Jn returns the order-n Bessel function of the first kind.

        Special cases are:

        Jn(n, ±Inf) = 0
        Jn(n, NaN) = NaN
        

        func Ldexp

        func Ldexp(frac float64, exp int) float64

        Ldexp is the inverse of Frexp. It returns frac × 2**exp.

        Special cases are:

        Ldexp(±0, exp) = ±0
        Ldexp(±Inf, exp) = ±Inf
        Ldexp(NaN, exp) = NaN
        

        func Lgamma

        func Lgamma(x float64) (lgamma float64, sign int)

        Lgamma returns the natural logarithm and sign (-1 or +1) of Gamma(x).

        Special cases are:

        Lgamma(+Inf) = +Inf
        Lgamma(0) = +Inf
        Lgamma(-integer) = +Inf
        Lgamma(-Inf) = -Inf
        Lgamma(NaN) = NaN
        

        func Log

        func Log(x float64) float64

        Log returns the natural logarithm of x.

        Special cases are:

        Log(+Inf) = +Inf
        Log(0) = -Inf
        Log(x < 0) = NaN
        Log(NaN) = NaN
        

        Example

        Code:

        x := math.Log(1)
        fmt.Printf("%.1f\n", x)
        
        y := math.Log(2.7183)
        fmt.Printf("%.1f\n", y)
        

        Output:

        0.0
        1.0
        

        func Log10

        func Log10(x float64) float64

        Log10 returns the decimal logarithm of x. The special cases are the same as for Log.

        Example

        Code:

        fmt.Printf("%.1f", math.Log10(100))
        

        Output:

        2.0
        

        func Log1p

        func Log1p(x float64) float64

        Log1p returns the natural logarithm of 1 plus its argument x. It is more accurate than Log(1 + x) when x is near zero.

        Special cases are:

        Log1p(+Inf) = +Inf
        Log1p(±0) = ±0
        Log1p(-1) = -Inf
        Log1p(x < -1) = NaN
        Log1p(NaN) = NaN
        

        func Log2

        func Log2(x float64) float64

        Log2 returns the binary logarithm of x. The special cases are the same as for Log.

        Example

        Code:

        fmt.Printf("%.1f", math.Log2(256))
        

        Output:

        8.0
        

        func Logb

        func Logb(x float64) float64

        Logb returns the binary exponent of x.

        Special cases are:

        Logb(±Inf) = +Inf
        Logb(0) = -Inf
        Logb(NaN) = NaN
        

        func Max

        func Max(x, y float64) float64

        Max returns the larger of x or y.

        Special cases are:

        Max(x, +Inf) = Max(+Inf, x) = +Inf
        Max(x, NaN) = Max(NaN, x) = NaN
        Max(+0, ±0) = Max(±0, +0) = +0
        Max(-0, -0) = -0
        

        Note that this differs from the built-in function max when called with NaN and +Inf.

        func Min

        func Min(x, y float64) float64

        Min returns the smaller of x or y.

        Special cases are:

        Min(x, -Inf) = Min(-Inf, x) = -Inf
        Min(x, NaN) = Min(NaN, x) = NaN
        Min(-0, ±0) = Min(±0, -0) = -0
        

        Note that this differs from the built-in function min when called with NaN and -Inf.

        func Mod

        func Mod(x, y float64) float64

        Mod returns the floating-point remainder of x/y. The magnitude of the result is less than y and its sign agrees with that of x.

        Special cases are:

        Mod(±Inf, y) = NaN
        Mod(NaN, y) = NaN
        Mod(x, 0) = NaN
        Mod(x, ±Inf) = x
        Mod(x, NaN) = NaN
        

        Example

        Code:

        c := math.Mod(7, 4)
        fmt.Printf("%.1f", c)
        

        Output:

        3.0
        

        func Modf

        func Modf(f float64) (int float64, frac float64)

        Modf returns integer and fractional floating-point numbers that sum to f. Both values have the same sign as f.

        Special cases are:

        Modf(±Inf) = ±Inf, NaN
        Modf(NaN) = NaN, NaN
        

        Example

        Code:

        int, frac := math.Modf(3.14)
        fmt.Printf("%.2f, %.2f\n", int, frac)
        
        int, frac = math.Modf(-2.71)
        fmt.Printf("%.2f, %.2f\n", int, frac)
        

        Output:

        3.00, 0.14
        -2.00, -0.71
        

        func NaN

        func NaN() float64

        NaN returns an IEEE 754 “not-a-number” value.

        func Nextafter

        func Nextafter(x, y float64) (r float64)

        Nextafter returns the next representable float64 value after x towards y.

        Special cases are:

        Nextafter(x, x)   = x
        Nextafter(NaN, y) = NaN
        Nextafter(x, NaN) = NaN
        

        func Nextafter32

        func Nextafter32(x, y float32) (r float32)

        Nextafter32 returns the next representable float32 value after x towards y.

        Special cases are:

        Nextafter32(x, x)   = x
        Nextafter32(NaN, y) = NaN
        Nextafter32(x, NaN) = NaN
        

        func Pow

        func Pow(x, y float64) float64

        Pow returns x**y, the base-x exponential of y.

        Special cases are (in order):

        Pow(x, ±0) = 1 for any x
        Pow(1, y) = 1 for any y
        Pow(x, 1) = x for any x
        Pow(NaN, y) = NaN
        Pow(x, NaN) = NaN
        Pow(±0, y) = ±Inf for y an odd integer < 0
        Pow(±0, -Inf) = +Inf
        Pow(±0, +Inf) = +0
        Pow(±0, y) = +Inf for finite y < 0 and not an odd integer
        Pow(±0, y) = ±0 for y an odd integer > 0
        Pow(±0, y) = +0 for finite y > 0 and not an odd integer
        Pow(-1, ±Inf) = 1
        Pow(x, +Inf) = +Inf for |x| > 1
        Pow(x, -Inf) = +0 for |x| > 1
        Pow(x, +Inf) = +0 for |x| < 1
        Pow(x, -Inf) = +Inf for |x| < 1
        Pow(+Inf, y) = +Inf for y > 0
        Pow(+Inf, y) = +0 for y < 0
        Pow(-Inf, y) = Pow(-0, -y)
        Pow(x, y) = NaN for finite x < 0 and finite non-integer y
        

        Example

        Code:

        c := math.Pow(2, 3)
        fmt.Printf("%.1f", c)
        

        Output:

        8.0
        

        func Pow10

        func Pow10(n int) float64

        Pow10 returns 10**n, the base-10 exponential of n.

        Special cases are:

        Pow10(n) =    0 for n < -323
        Pow10(n) = +Inf for n > 308
        

        Example

        Code:

        c := math.Pow10(2)
        fmt.Printf("%.1f", c)
        

        Output:

        100.0
        

        func Remainder

        func Remainder(x, y float64) float64

        Remainder returns the IEEE 754 floating-point remainder of x/y.

        Special cases are:

        Remainder(±Inf, y) = NaN
        Remainder(NaN, y) = NaN
        Remainder(x, 0) = NaN
        Remainder(x, ±Inf) = x
        Remainder(x, NaN) = NaN
        

        Example

        Code:

        fmt.Printf("%.1f", math.Remainder(100, 30))
        

        Output:

        10.0
        

        func Round

        func Round(x float64) float64

        Round returns the nearest integer, rounding half away from zero.

        Special cases are:

        Round(±0) = ±0
        Round(±Inf) = ±Inf
        Round(NaN) = NaN
        

        Example

        Code:

        p := math.Round(10.5)
        fmt.Printf("%.1f\n", p)
        
        n := math.Round(-10.5)
        fmt.Printf("%.1f\n", n)
        

        Output:

        11.0
        -11.0
        

        func RoundToEven

        func RoundToEven(x float64) float64

        RoundToEven returns the nearest integer, rounding ties to even.

        Special cases are:

        RoundToEven(±0) = ±0
        RoundToEven(±Inf) = ±Inf
        RoundToEven(NaN) = NaN
        

        Example

        Code:

        u := math.RoundToEven(11.5)
        fmt.Printf("%.1f\n", u)
        
        d := math.RoundToEven(12.5)
        fmt.Printf("%.1f\n", d)
        

        Output:

        12.0
        12.0
        

        func Signbit

        func Signbit(x float64) bool

        Signbit reports whether x is negative or negative zero.

        func Sin

        func Sin(x float64) float64

        Sin returns the sine of the radian argument x.

        Special cases are:

        Sin(±0) = ±0
        Sin(±Inf) = NaN
        Sin(NaN) = NaN
        

        Example

        Code:

        fmt.Printf("%.2f", math.Sin(math.Pi))
        

        Output:

        0.00
        

        func Sincos

        func Sincos(x float64) (sin, cos float64)

        Sincos returns Sin(x), Cos(x).

        Special cases are:

        Sincos(±0) = ±0, 1
        Sincos(±Inf) = NaN, NaN
        Sincos(NaN) = NaN, NaN
        

        Example

        Code:

        sin, cos := math.Sincos(0)
        fmt.Printf("%.2f, %.2f", sin, cos)
        

        Output:

        0.00, 1.00
        

        func Sinh

        func Sinh(x float64) float64

        Sinh returns the hyperbolic sine of x.

        Special cases are:

        Sinh(±0) = ±0
        Sinh(±Inf) = ±Inf
        Sinh(NaN) = NaN
        

        Example

        Code:

        fmt.Printf("%.2f", math.Sinh(0))
        

        Output:

        0.00
        

        func Sqrt

        func Sqrt(x float64) float64

        Sqrt returns the square root of x.

        Special cases are:

        Sqrt(+Inf) = +Inf
        Sqrt(±0) = ±0
        Sqrt(x < 0) = NaN
        Sqrt(NaN) = NaN
        

        Example

        Code:

        const (
            a = 3
            b = 4
        )
        c := math.Sqrt(a*a + b*b)
        fmt.Printf("%.1f", c)
        

        Output:

        5.0
        

        func Tan

        func Tan(x float64) float64

        Tan returns the tangent of the radian argument x.

        Special cases are:

        Tan(±0) = ±0
        Tan(±Inf) = NaN
        Tan(NaN) = NaN
        

        Example

        Code:

        fmt.Printf("%.2f", math.Tan(0))
        

        Output:

        0.00
        

        func Tanh

        func Tanh(x float64) float64

        Tanh returns the hyperbolic tangent of x.

        Special cases are:

        Tanh(±0) = ±0
        Tanh(±Inf) = ±1
        Tanh(NaN) = NaN
        

        Example

        Code:

        fmt.Printf("%.2f", math.Tanh(0))
        

        Output:

        0.00
        

        func Trunc

        func Trunc(x float64) float64

        Trunc returns the integer value of x.

        Special cases are:

        Trunc(±0) = ±0
        Trunc(±Inf) = ±Inf
        Trunc(NaN) = NaN
        

        Example

        Code:

        fmt.Printf("%.2f\n", math.Trunc(math.Pi))
        fmt.Printf("%.2f\n", math.Trunc(-1.2345))
        

        Output:

        3.00
        -1.00
        

        func Y0

        func Y0(x float64) float64

        Y0 returns the order-zero Bessel function of the second kind.

        Special cases are:

        Y0(+Inf) = 0
        Y0(0) = -Inf
        Y0(x < 0) = NaN
        Y0(NaN) = NaN
        

        func Y1

        func Y1(x float64) float64

        Y1 returns the order-one Bessel function of the second kind.

        Special cases are:

        Y1(+Inf) = 0
        Y1(0) = -Inf
        Y1(x < 0) = NaN
        Y1(NaN) = NaN
        

        func Yn

        func Yn(n int, x float64) float64

        Yn returns the order-n Bessel function of the second kind.

        Special cases are:

        Yn(n, +Inf) = 0
        Yn(n ≥ 0, 0) = -Inf
        Yn(n < 0, 0) = +Inf if n is odd, -Inf if n is even
        Yn(n, x < 0) = NaN
        Yn(n, NaN) = NaN
        

        Subdirectories

        Name Synopsis
        ..
        big Package big implements arbitrary-precision arithmetic (big numbers).
        bits Package bits implements bit counting and manipulation functions for the predeclared unsigned integer types.
        cmplx Package cmplx provides basic constants and mathematical functions for complex numbers.
        rand Package rand implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.
        v2 Package rand implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.
        big - Go Documentation Server
        ...

        Package big

        import "math/big"
        Overview
        Index
        Examples

        Overview ▾

        Package big implements arbitrary-precision arithmetic (big numbers). The following numeric types are supported:

        Int    signed integers
        Rat    rational numbers
        Float  floating-point numbers
        

        The zero value for an Int, Rat, or Float correspond to 0. Thus, new values can be declared in the usual ways and denote 0 without further initialization:

        var x Int        // &x is an *Int of value 0
        var r = &Rat{}   // r is a *Rat of value 0
        y := new(Float)  // y is a *Float of value 0
        

        Alternatively, new values can be allocated and initialized with factory functions of the form:

        func NewT(v V) *T
        

        For instance, NewInt(x) returns an *Int set to the value of the int64 argument x, NewRat(a, b) returns a *Rat set to the fraction a/b where a and b are int64 values, and NewFloat(f) returns a *Float initialized to the float64 argument f. More flexibility is provided with explicit setters, for instance:

        var z1 Int
        z1.SetUint64(123)                 // z1 := 123
        z2 := new(Rat).SetFloat64(1.25)   // z2 := 5/4
        z3 := new(Float).SetInt(z1)       // z3 := 123.0
        

        Setters, numeric operations and predicates are represented as methods of the form:

        func (z *T) SetV(v V) *T          // z = v
        func (z *T) Unary(x *T) *T        // z = unary x
        func (z *T) Binary(x, y *T) *T    // z = x binary y
        func (x *T) Pred() P              // p = pred(x)
        

        with T one of Int, Rat, or Float. For unary and binary operations, the result is the receiver (usually named z in that case; see below); if it is one of the operands x or y it may be safely overwritten (and its memory reused).

        Arithmetic expressions are typically written as a sequence of individual method calls, with each call corresponding to an operation. The receiver denotes the result and the method arguments are the operation's operands. For instance, given three *Int values a, b and c, the invocation

        c.Add(a, b)
        

        computes the sum a + b and stores the result in c, overwriting whatever value was held in c before. Unless specified otherwise, operations permit aliasing of parameters, so it is perfectly ok to write

        sum.Add(sum, x)
        

        to accumulate values x in a sum.

        (By always passing in a result value via the receiver, memory use can be much better controlled. Instead of having to allocate new memory for each result, an operation can reuse the space allocated for the result value, and overwrite that value with the new result in the process.)

        Notational convention: Incoming method parameters (including the receiver) are named consistently in the API to clarify their use. Incoming operands are usually named x, y, a, b, and so on, but never z. A parameter specifying the result is named z (typically the receiver).

        For instance, the arguments for (*Int).Add are named x and y, and because the receiver specifies the result destination, it is called z:

        func (z *Int) Add(x, y *Int) *Int
        

        Methods of this form typically return the incoming receiver as well, to enable simple call chaining.

        Methods which don't require a result value to be passed in (for instance, Int.Sign), simply return the result. In this case, the receiver is typically the first operand, named x:

        func (x *Int) Sign() int
        

        Various methods support conversions between strings and corresponding numeric values, and vice versa: *Int, *Rat, and *Float values implement the Stringer interface for a (default) string representation of the value, but also provide SetString methods to initialize a value from a string in a variety of supported formats (see the respective SetString documentation).

        Finally, *Int, *Rat, and *Float satisfy fmt.Scanner for scanning and (except for *Rat) the Formatter interface for formatted printing.

        Example (EConvergents)

        This example demonstrates how to use big.Rat to compute the first 15 terms in the sequence of rational convergents for the constant e (base of natural logarithm).

        Code:

        package big_test
        
        import (
            "fmt"
            "math/big"
        )
        
        // Use the classic continued fraction for e
        //
        //	e = [1; 0, 1, 1, 2, 1, 1, ... 2n, 1, 1, ...]
        //
        // i.e., for the nth term, use
        //
        //	   1          if   n mod 3 != 1
        //	(n-1)/3 * 2   if   n mod 3 == 1
        func recur(n, lim int64) *big.Rat {
            term := new(big.Rat)
            if n%3 != 1 {
                term.SetInt64(1)
            } else {
                term.SetInt64((n - 1) / 3 * 2)
            }
        
            if n > lim {
                return term
            }
        
            // Directly initialize frac as the fractional
            // inverse of the result of recur.
            frac := new(big.Rat).Inv(recur(n+1, lim))
        
            return term.Add(term, frac)
        }
        
        // This example demonstrates how to use big.Rat to compute the
        // first 15 terms in the sequence of rational convergents for
        // the constant e (base of natural logarithm).
        func Example_eConvergents() {
            for i := 1; i <= 15; i++ {
                r := recur(0, int64(i))
        
                // Print r both as a fraction and as a floating-point number.
                // Since big.Rat implements fmt.Formatter, we can use %-13s to
                // get a left-aligned string representation of the fraction.
                fmt.Printf("%-13s = %s\n", r, r.FloatString(8))
            }
        
            // Output:
            // 2/1           = 2.00000000
            // 3/1           = 3.00000000
            // 8/3           = 2.66666667
            // 11/4          = 2.75000000
            // 19/7          = 2.71428571
            // 87/32         = 2.71875000
            // 106/39        = 2.71794872
            // 193/71        = 2.71830986
            // 1264/465      = 2.71827957
            // 1457/536      = 2.71828358
            // 2721/1001     = 2.71828172
            // 23225/8544    = 2.71828184
            // 25946/9545    = 2.71828182
            // 49171/18089   = 2.71828183
            // 517656/190435 = 2.71828183
        }
        

        Example (Fibonacci)

        This example demonstrates how to use big.Int to compute the smallest Fibonacci number with 100 decimal digits and to test whether it is prime.

        Code:

        // Initialize two big ints with the first two numbers in the sequence.
        a := big.NewInt(0)
        b := big.NewInt(1)
        
        // Initialize limit as 10^99, the smallest integer with 100 digits.
        var limit big.Int
        limit.Exp(big.NewInt(10), big.NewInt(99), nil)
        
        // Loop while a is smaller than 1e100.
        for a.Cmp(&limit) < 0 {
            // Compute the next Fibonacci number, storing it in a.
            a.Add(a, b)
            // Swap a and b so that b is the next number in the sequence.
            a, b = b, a
        }
        fmt.Println(a) // 100-digit Fibonacci number
        
        // Test a for primality.
        // (ProbablyPrimes' argument sets the number of Miller-Rabin
        // rounds to be performed. 20 is a good value.)
        fmt.Println(a.ProbablyPrime(20))
        
        

        Output:

        1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757
        false
        

        Example (Sqrt2)

        This example shows how to use big.Float to compute the square root of 2 with a precision of 200 bits, and how to print the result as a decimal number.

        Code:

        // We'll do computations with 200 bits of precision in the mantissa.
        const prec = 200
        
        // Compute the square root of 2 using Newton's Method. We start with
        // an initial estimate for sqrt(2), and then iterate:
        //     x_{n+1} = 1/2 * ( x_n + (2.0 / x_n) )
        
        // Since Newton's Method doubles the number of correct digits at each
        // iteration, we need at least log_2(prec) steps.
        steps := int(math.Log2(prec))
        
        // Initialize values we need for the computation.
        two := new(big.Float).SetPrec(prec).SetInt64(2)
        half := new(big.Float).SetPrec(prec).SetFloat64(0.5)
        
        // Use 1 as the initial estimate.
        x := new(big.Float).SetPrec(prec).SetInt64(1)
        
        // We use t as a temporary variable. There's no need to set its precision
        // since big.Float values with unset (== 0) precision automatically assume
        // the largest precision of the arguments when used as the result (receiver)
        // of a big.Float operation.
        t := new(big.Float)
        
        // Iterate.
        for i := 0; i <= steps; i++ {
            t.Quo(two, x)  // t = 2.0 / x_n
            t.Add(x, t)    // t = x_n + (2.0 / x_n)
            x.Mul(half, t) // x_{n+1} = 0.5 * t
        }
        
        // We can use the usual fmt.Printf verbs since big.Float implements fmt.Formatter
        fmt.Printf("sqrt(2) = %.50f\n", x)
        
        // Print the error between 2 and x*x.
        t.Mul(x, x) // t = x*x
        fmt.Printf("error = %e\n", t.Sub(two, t))
        
        

        Output:

        sqrt(2) = 1.41421356237309504880168872420969807856967187537695
        error = 0.000000e+00
        

        Index ▾

        Constants
        func Jacobi(x, y *Int) int
        type Accuracy
            func (i Accuracy) String() string
        type ErrNaN
            func (err ErrNaN) Error() string
        type Float
            func NewFloat(x float64) *Float
            func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error)
            func (z *Float) Abs(x *Float) *Float
            func (x *Float) Acc() Accuracy
            func (z *Float) Add(x, y *Float) *Float
            func (x *Float) Append(buf []byte, fmt byte, prec int) []byte
            func (x *Float) Cmp(y *Float) int
            func (z *Float) Copy(x *Float) *Float
            func (x *Float) Float32() (float32, Accuracy)
            func (x *Float) Float64() (float64, Accuracy)
            func (x *Float) Format(s fmt.State, format rune)
            func (z *Float) GobDecode(buf []byte) error
            func (x *Float) GobEncode() ([]byte, error)
            func (x *Float) Int(z *Int) (*Int, Accuracy)
            func (x *Float) Int64() (int64, Accuracy)
            func (x *Float) IsInf() bool
            func (x *Float) IsInt() bool
            func (x *Float) MantExp(mant *Float) (exp int)
            func (x *Float) MarshalText() (text []byte, err error)
            func (x *Float) MinPrec() uint
            func (x *Float) Mode() RoundingMode
            func (z *Float) Mul(x, y *Float) *Float
            func (z *Float) Neg(x *Float) *Float
            func (z *Float) Parse(s string, base int) (f *Float, b int, err error)
            func (x *Float) Prec() uint
            func (z *Float) Quo(x, y *Float) *Float
            func (x *Float) Rat(z *Rat) (*Rat, Accuracy)
            func (z *Float) Scan(s fmt.ScanState, ch rune) error
            func (z *Float) Set(x *Float) *Float
            func (z *Float) SetFloat64(x float64) *Float
            func (z *Float) SetInf(signbit bool) *Float
            func (z *Float) SetInt(x *Int) *Float
            func (z *Float) SetInt64(x int64) *Float
            func (z *Float) SetMantExp(mant *Float, exp int) *Float
            func (z *Float) SetMode(mode RoundingMode) *Float
            func (z *Float) SetPrec(prec uint) *Float
            func (z *Float) SetRat(x *Rat) *Float
            func (z *Float) SetString(s string) (*Float, bool)
            func (z *Float) SetUint64(x uint64) *Float
            func (x *Float) Sign() int
            func (x *Float) Signbit() bool
            func (z *Float) Sqrt(x *Float) *Float
            func (x *Float) String() string
            func (z *Float) Sub(x, y *Float) *Float
            func (x *Float) Text(format byte, prec int) string
            func (x *Float) Uint64() (uint64, Accuracy)
            func (z *Float) UnmarshalText(text []byte) error
        type Int
            func NewInt(x int64) *Int
            func (z *Int) Abs(x *Int) *Int
            func (z *Int) Add(x, y *Int) *Int
            func (z *Int) And(x, y *Int) *Int
            func (z *Int) AndNot(x, y *Int) *Int
            func (x *Int) Append(buf []byte, base int) []byte
            func (z *Int) Binomial(n, k int64) *Int
            func (x *Int) Bit(i int) uint
            func (x *Int) BitLen() int
            func (x *Int) Bits() []Word
            func (x *Int) Bytes() []byte
            func (x *Int) Cmp(y *Int) (r int)
            func (x *Int) CmpAbs(y *Int) int
            func (z *Int) Div(x, y *Int) *Int
            func (z *Int) DivMod(x, y, m *Int) (*Int, *Int)
            func (z *Int) Exp(x, y, m *Int) *Int
            func (x *Int) FillBytes(buf []byte) []byte
            func (x *Int) Float64() (float64, Accuracy)
            func (x *Int) Format(s fmt.State, ch rune)
            func (z *Int) GCD(x, y, a, b *Int) *Int
            func (z *Int) GobDecode(buf []byte) error
            func (x *Int) GobEncode() ([]byte, error)
            func (x *Int) Int64() int64
            func (x *Int) IsInt64() bool
            func (x *Int) IsUint64() bool
            func (z *Int) Lsh(x *Int, n uint) *Int
            func (x *Int) MarshalJSON() ([]byte, error)
            func (x *Int) MarshalText() (text []byte, err error)
            func (z *Int) Mod(x, y *Int) *Int
            func (z *Int) ModInverse(g, n *Int) *Int
            func (z *Int) ModSqrt(x, p *Int) *Int
            func (z *Int) Mul(x, y *Int) *Int
            func (z *Int) MulRange(a, b int64) *Int
            func (z *Int) Neg(x *Int) *Int
            func (z *Int) Not(x *Int) *Int
            func (z *Int) Or(x, y *Int) *Int
            func (x *Int) ProbablyPrime(n int) bool
            func (z *Int) Quo(x, y *Int) *Int
            func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int)
            func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int
            func (z *Int) Rem(x, y *Int) *Int
            func (z *Int) Rsh(x *Int, n uint) *Int
            func (z *Int) Scan(s fmt.ScanState, ch rune) error
            func (z *Int) Set(x *Int) *Int
            func (z *Int) SetBit(x *Int, i int, b uint) *Int
            func (z *Int) SetBits(abs []Word) *Int
            func (z *Int) SetBytes(buf []byte) *Int
            func (z *Int) SetInt64(x int64) *Int
            func (z *Int) SetString(s string, base int) (*Int, bool)
            func (z *Int) SetUint64(x uint64) *Int
            func (x *Int) Sign() int
            func (z *Int) Sqrt(x *Int) *Int
            func (x *Int) String() string
            func (z *Int) Sub(x, y *Int) *Int
            func (x *Int) Text(base int) string
            func (x *Int) TrailingZeroBits() uint
            func (x *Int) Uint64() uint64
            func (z *Int) UnmarshalJSON(text []byte) error
            func (z *Int) UnmarshalText(text []byte) error
            func (z *Int) Xor(x, y *Int) *Int
        type Rat
            func NewRat(a, b int64) *Rat
            func (z *Rat) Abs(x *Rat) *Rat
            func (z *Rat) Add(x, y *Rat) *Rat
            func (x *Rat) Cmp(y *Rat) int
            func (x *Rat) Denom() *Int
            func (x *Rat) Float32() (f float32, exact bool)
            func (x *Rat) Float64() (f float64, exact bool)
            func (x *Rat) FloatPrec() (n int, exact bool)
            func (x *Rat) FloatString(prec int) string
            func (z *Rat) GobDecode(buf []byte) error
            func (x *Rat) GobEncode() ([]byte, error)
            func (z *Rat) Inv(x *Rat) *Rat
            func (x *Rat) IsInt() bool
            func (x *Rat) MarshalText() (text []byte, err error)
            func (z *Rat) Mul(x, y *Rat) *Rat
            func (z *Rat) Neg(x *Rat) *Rat
            func (x *Rat) Num() *Int
            func (z *Rat) Quo(x, y *Rat) *Rat
            func (x *Rat) RatString() string
            func (z *Rat) Scan(s fmt.ScanState, ch rune) error
            func (z *Rat) Set(x *Rat) *Rat
            func (z *Rat) SetFloat64(f float64) *Rat
            func (z *Rat) SetFrac(a, b *Int) *Rat
            func (z *Rat) SetFrac64(a, b int64) *Rat
            func (z *Rat) SetInt(x *Int) *Rat
            func (z *Rat) SetInt64(x int64) *Rat
            func (z *Rat) SetString(s string) (*Rat, bool)
            func (z *Rat) SetUint64(x uint64) *Rat
            func (x *Rat) Sign() int
            func (x *Rat) String() string
            func (z *Rat) Sub(x, y *Rat) *Rat
            func (z *Rat) UnmarshalText(text []byte) error
        type RoundingMode
            func (i RoundingMode) String() string
        type Word

        Package files

        accuracy_string.go arith.go arith_amd64.go arith_decl.go decimal.go doc.go float.go floatconv.go floatmarsh.go ftoa.go int.go intconv.go intmarsh.go nat.go natconv.go natdiv.go prime.go rat.go ratconv.go ratmarsh.go roundingmode_string.go sqrt.go

        Constants

        Exponent and precision limits.

        const (
            MaxExp  = math.MaxInt32  // largest supported exponent
            MinExp  = math.MinInt32  // smallest supported exponent
            MaxPrec = math.MaxUint32 // largest (theoretically) supported precision; likely memory-limited
        )

        MaxBase is the largest number base accepted for string conversions.

        const MaxBase = 10 + ('z' - 'a' + 1) + ('Z' - 'A' + 1)

        func Jacobi

        func Jacobi(x, y *Int) int

        Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0. The y argument must be an odd integer.

        type Accuracy

        Accuracy describes the rounding error produced by the most recent operation that generated a Float value, relative to the exact value.

        type Accuracy int8

        Constants describing the Accuracy of a Float.

        const (
            Below Accuracy = -1
            Exact Accuracy = 0
            Above Accuracy = +1
        )

        func (Accuracy) String

        func (i Accuracy) String() string

        type ErrNaN

        An ErrNaN panic is raised by a Float operation that would lead to a NaN under IEEE-754 rules. An ErrNaN implements the error interface.

        type ErrNaN struct {
            // contains filtered or unexported fields
        }
        

        func (ErrNaN) Error

        func (err ErrNaN) Error() string

        type Float

        A nonzero finite Float represents a multi-precision floating point number

        sign × mantissa × 2**exponent
        

        with 0.5 <= mantissa < 1.0, and MinExp <= exponent <= MaxExp. A Float may also be zero (+0, -0) or infinite (+Inf, -Inf). All Floats are ordered, and the ordering of two Floats x and y is defined by x.Cmp(y).

        Each Float value also has a precision, rounding mode, and accuracy. The precision is the maximum number of mantissa bits available to represent the value. The rounding mode specifies how a result should be rounded to fit into the mantissa bits, and accuracy describes the rounding error with respect to the exact result.

        Unless specified otherwise, all operations (including setters) that specify a *Float variable for the result (usually via the receiver with the exception of Float.MantExp), round the numeric result according to the precision and rounding mode of the result variable.

        If the provided result precision is 0 (see below), it is set to the precision of the argument with the largest precision value before any rounding takes place, and the rounding mode remains unchanged. Thus, uninitialized Floats provided as result arguments will have their precision set to a reasonable value determined by the operands, and their mode is the zero value for RoundingMode (ToNearestEven).

        By setting the desired precision to 24 or 53 and using matching rounding mode (typically ToNearestEven), Float operations produce the same results as the corresponding float32 or float64 IEEE-754 arithmetic for operands that correspond to normal (i.e., not denormal) float32 or float64 numbers. Exponent underflow and overflow lead to a 0 or an Infinity for different values than IEEE-754 because Float exponents have a much larger range.

        The zero (uninitialized) value for a Float is ready to use and represents the number +0.0 exactly, with precision 0 and rounding mode ToNearestEven.

        Operations always take pointer arguments (*Float) rather than Float values, and each unique Float value requires its own unique *Float pointer. To "copy" a Float value, an existing (or newly allocated) Float must be set to a new value using the Float.Set method; shallow copies of Floats are not supported and may lead to errors.

        type Float struct {
            // contains filtered or unexported fields
        }
        

        Example (Shift)

        Code:

        // Implement Float "shift" by modifying the (binary) exponents directly.
        for s := -5; s <= 5; s++ {
            x := big.NewFloat(0.5)
            x.SetMantExp(x, x.MantExp(nil)+s) // shift x by s
            fmt.Println(x)
        }
        

        Output:

        0.015625
        0.03125
        0.0625
        0.125
        0.25
        0.5
        1
        2
        4
        8
        16
        

        func NewFloat

        func NewFloat(x float64) *Float

        NewFloat allocates and returns a new Float set to x, with precision 53 and rounding mode ToNearestEven. NewFloat panics with ErrNaN if x is a NaN.

        func ParseFloat

        func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error)

        ParseFloat is like f.Parse(s, base) with f set to the given precision and rounding mode.

        func (*Float) Abs

        func (z *Float) Abs(x *Float) *Float

        Abs sets z to the (possibly rounded) value |x| (the absolute value of x) and returns z.

        func (*Float) Acc

        func (x *Float) Acc() Accuracy

        Acc returns the accuracy of x produced by the most recent operation, unless explicitly documented otherwise by that operation.

        func (*Float) Add

        func (z *Float) Add(x, y *Float) *Float

        Add sets z to the rounded sum x+y and returns z. If z's precision is 0, it is changed to the larger of x's or y's precision before the operation. Rounding is performed according to z's precision and rounding mode; and z's accuracy reports the result error relative to the exact (not rounded) result. Add panics with ErrNaN if x and y are infinities with opposite signs. The value of z is undefined in that case.

        Example

        Code:

        // Operate on numbers of different precision.
        var x, y, z big.Float
        x.SetInt64(1000)          // x is automatically set to 64bit precision
        y.SetFloat64(2.718281828) // y is automatically set to 53bit precision
        z.SetPrec(32)
        z.Add(&x, &y)
        fmt.Printf("x = %.10g (%s, prec = %d, acc = %s)\n", &x, x.Text('p', 0), x.Prec(), x.Acc())
        fmt.Printf("y = %.10g (%s, prec = %d, acc = %s)\n", &y, y.Text('p', 0), y.Prec(), y.Acc())
        fmt.Printf("z = %.10g (%s, prec = %d, acc = %s)\n", &z, z.Text('p', 0), z.Prec(), z.Acc())
        

        Output:

        x = 1000 (0x.fap+10, prec = 64, acc = Exact)
        y = 2.718281828 (0x.adf85458248cd8p+2, prec = 53, acc = Exact)
        z = 1002.718282 (0x.faadf854p+10, prec = 32, acc = Below)
        

        func (*Float) Append

        func (x *Float) Append(buf []byte, fmt byte, prec int) []byte

        Append appends to buf the string form of the floating-point number x, as generated by x.Text, and returns the extended buffer.

        func (*Float) Cmp

        func (x *Float) Cmp(y *Float) int

        Cmp compares x and y and returns:

        -1 if x <  y
         0 if x == y (incl. -0 == 0, -Inf == -Inf, and +Inf == +Inf)
        +1 if x >  y
        

        Example

        Code:

        inf := math.Inf(1)
        zero := 0.0
        
        operands := []float64{-inf, -1.2, -zero, 0, +1.2, +inf}
        
        fmt.Println("   x     y  cmp")
        fmt.Println("---------------")
        for _, x64 := range operands {
            x := big.NewFloat(x64)
            for _, y64 := range operands {
                y := big.NewFloat(y64)
                fmt.Printf("%4g  %4g  %3d\n", x, y, x.Cmp(y))
            }
            fmt.Println()
        }
        
        

        Output:

           x     y  cmp
        ---------------
        -Inf  -Inf    0
        -Inf  -1.2   -1
        -Inf    -0   -1
        -Inf     0   -1
        -Inf   1.2   -1
        -Inf  +Inf   -1
        
        -1.2  -Inf    1
        -1.2  -1.2    0
        -1.2    -0   -1
        -1.2     0   -1
        -1.2   1.2   -1
        -1.2  +Inf   -1
        
          -0  -Inf    1
          -0  -1.2    1
          -0    -0    0
          -0     0    0
          -0   1.2   -1
          -0  +Inf   -1
        
           0  -Inf    1
           0  -1.2    1
           0    -0    0
           0     0    0
           0   1.2   -1
           0  +Inf   -1
        
         1.2  -Inf    1
         1.2  -1.2    1
         1.2    -0    1
         1.2     0    1
         1.2   1.2    0
         1.2  +Inf   -1
        
        +Inf  -Inf    1
        +Inf  -1.2    1
        +Inf    -0    1
        +Inf     0    1
        +Inf   1.2    1
        +Inf  +Inf    0
        

        func (*Float) Copy

        func (z *Float) Copy(x *Float) *Float

        Copy sets z to x, with the same precision, rounding mode, and accuracy as x, and returns z. x is not changed even if z and x are the same.

        func (*Float) Float32

        func (x *Float) Float32() (float32, Accuracy)

        Float32 returns the float32 value nearest to x. If x is too small to be represented by a float32 (|x| < math.SmallestNonzeroFloat32), the result is (0, Below) or (-0, Above), respectively, depending on the sign of x. If x is too large to be represented by a float32 (|x| > math.MaxFloat32), the result is (+Inf, Above) or (-Inf, Below), depending on the sign of x.

        func (*Float) Float64

        func (x *Float) Float64() (float64, Accuracy)

        Float64 returns the float64 value nearest to x. If x is too small to be represented by a float64 (|x| < math.SmallestNonzeroFloat64), the result is (0, Below) or (-0, Above), respectively, depending on the sign of x. If x is too large to be represented by a float64 (|x| > math.MaxFloat64), the result is (+Inf, Above) or (-Inf, Below), depending on the sign of x.

        func (*Float) Format

        func (x *Float) Format(s fmt.State, format rune)

        Format implements fmt.Formatter. It accepts all the regular formats for floating-point numbers ('b', 'e', 'E', 'f', 'F', 'g', 'G', 'x') as well as 'p' and 'v'. See (*Float).Text for the interpretation of 'p'. The 'v' format is handled like 'g'. Format also supports specification of the minimum precision in digits, the output field width, as well as the format flags '+' and ' ' for sign control, '0' for space or zero padding, and '-' for left or right justification. See the fmt package for details.

        func (*Float) GobDecode

        func (z *Float) GobDecode(buf []byte) error

        GobDecode implements the encoding/gob.GobDecoder interface. The result is rounded per the precision and rounding mode of z unless z's precision is 0, in which case z is set exactly to the decoded value.

        func (*Float) GobEncode

        func (x *Float) GobEncode() ([]byte, error)

        GobEncode implements the encoding/gob.GobEncoder interface. The Float value and all its attributes (precision, rounding mode, accuracy) are marshaled.

        func (*Float) Int

        func (x *Float) Int(z *Int) (*Int, Accuracy)

        Int returns the result of truncating x towards zero; or nil if x is an infinity. The result is Exact if x.IsInt(); otherwise it is Below for x > 0, and Above for x < 0. If a non-nil *Int argument z is provided, Int stores the result in z instead of allocating a new Int.

        func (*Float) Int64

        func (x *Float) Int64() (int64, Accuracy)

        Int64 returns the integer resulting from truncating x towards zero. If math.MinInt64 <= x <= math.MaxInt64, the result is Exact if x is an integer, and Above (x < 0) or Below (x > 0) otherwise. The result is (math.MinInt64, Above) for x < math.MinInt64, and (math.MaxInt64, Below) for x > math.MaxInt64.

        func (*Float) IsInf

        func (x *Float) IsInf() bool

        IsInf reports whether x is +Inf or -Inf.

        func (*Float) IsInt

        func (x *Float) IsInt() bool

        IsInt reports whether x is an integer. ±Inf values are not integers.

        func (*Float) MantExp

        func (x *Float) MantExp(mant *Float) (exp int)

        MantExp breaks x into its mantissa and exponent components and returns the exponent. If a non-nil mant argument is provided its value is set to the mantissa of x, with the same precision and rounding mode as x. The components satisfy x == mant × 2**exp, with 0.5 <= |mant| < 1.0. Calling MantExp with a nil argument is an efficient way to get the exponent of the receiver.

        Special cases are:

        (  ±0).MantExp(mant) = 0, with mant set to   ±0
        (±Inf).MantExp(mant) = 0, with mant set to ±Inf
        

        x and mant may be the same in which case x is set to its mantissa value.

        func (*Float) MarshalText

        func (x *Float) MarshalText() (text []byte, err error)

        MarshalText implements the encoding.TextMarshaler interface. Only the Float value is marshaled (in full precision), other attributes such as precision or accuracy are ignored.

        func (*Float) MinPrec

        func (x *Float) MinPrec() uint

        MinPrec returns the minimum precision required to represent x exactly (i.e., the smallest prec before x.SetPrec(prec) would start rounding x). The result is 0 for |x| == 0 and |x| == Inf.

        func (*Float) Mode

        func (x *Float) Mode() RoundingMode

        Mode returns the rounding mode of x.

        func (*Float) Mul

        func (z *Float) Mul(x, y *Float) *Float

        Mul sets z to the rounded product x*y and returns z. Precision, rounding, and accuracy reporting are as for Float.Add. Mul panics with ErrNaN if one operand is zero and the other operand an infinity. The value of z is undefined in that case.

        func (*Float) Neg

        func (z *Float) Neg(x *Float) *Float

        Neg sets z to the (possibly rounded) value of x with its sign negated, and returns z.

        func (*Float) Parse

        func (z *Float) Parse(s string, base int) (f *Float, b int, err error)

        Parse parses s which must contain a text representation of a floating- point number with a mantissa in the given conversion base (the exponent is always a decimal number), or a string representing an infinite value.

        For base 0, an underscore character “_” may appear between a base prefix and an adjacent digit, and between successive digits; such underscores do not change the value of the number, or the returned digit count. Incorrect placement of underscores is reported as an error if there are no other errors. If base != 0, underscores are not recognized and thus terminate scanning like any other character that is not a valid radix point or digit.

        It sets z to the (possibly rounded) value of the corresponding floating- point value, and returns z, the actual base b, and an error err, if any. The entire string (not just a prefix) must be consumed for success. If z's precision is 0, it is changed to 64 before rounding takes effect. The number must be of the form:

        number    = [ sign ] ( float | "inf" | "Inf" ) .
        sign      = "+" | "-" .
        float     = ( mantissa | prefix pmantissa ) [ exponent ] .
        prefix    = "0" [ "b" | "B" | "o" | "O" | "x" | "X" ] .
        mantissa  = digits "." [ digits ] | digits | "." digits .
        pmantissa = [ "_" ] digits "." [ digits ] | [ "_" ] digits | "." digits .
        exponent  = ( "e" | "E" | "p" | "P" ) [ sign ] digits .
        digits    = digit { [ "_" ] digit } .
        digit     = "0" ... "9" | "a" ... "z" | "A" ... "Z" .
        

        The base argument must be 0, 2, 8, 10, or 16. Providing an invalid base argument will lead to a run-time panic.

        For base 0, the number prefix determines the actual base: A prefix of “0b” or “0B” selects base 2, “0o” or “0O” selects base 8, and “0x” or “0X” selects base 16. Otherwise, the actual base is 10 and no prefix is accepted. The octal prefix "0" is not supported (a leading "0" is simply considered a "0").

        A "p" or "P" exponent indicates a base 2 (rather than base 10) exponent; for instance, "0x1.fffffffffffffp1023" (using base 0) represents the maximum float64 value. For hexadecimal mantissae, the exponent character must be one of 'p' or 'P', if present (an "e" or "E" exponent indicator cannot be distinguished from a mantissa digit).

        The returned *Float f is nil and the value of z is valid but not defined if an error is reported.

        func (*Float) Prec

        func (x *Float) Prec() uint

        Prec returns the mantissa precision of x in bits. The result may be 0 for |x| == 0 and |x| == Inf.

        func (*Float) Quo

        func (z *Float) Quo(x, y *Float) *Float

        Quo sets z to the rounded quotient x/y and returns z. Precision, rounding, and accuracy reporting are as for Float.Add. Quo panics with ErrNaN if both operands are zero or infinities. The value of z is undefined in that case.

        func (*Float) Rat

        func (x *Float) Rat(z *Rat) (*Rat, Accuracy)

        Rat returns the rational number corresponding to x; or nil if x is an infinity. The result is Exact if x is not an Inf. If a non-nil *Rat argument z is provided, Rat stores the result in z instead of allocating a new Rat.

        func (*Float) Scan

        func (z *Float) Scan(s fmt.ScanState, ch rune) error

        Scan is a support routine for fmt.Scanner; it sets z to the value of the scanned number. It accepts formats whose verbs are supported by fmt.Scan for floating point values, which are: 'b' (binary), 'e', 'E', 'f', 'F', 'g' and 'G'. Scan doesn't handle ±Inf.

        Example

        Code:

        // The Scan function is rarely used directly;
        // the fmt package recognizes it as an implementation of fmt.Scanner.
        f := new(big.Float)
        _, err := fmt.Sscan("1.19282e99", f)
        if err != nil {
            log.Println("error scanning value:", err)
        } else {
            fmt.Println(f)
        }
        

        Output:

        1.19282e+99
        

        func (*Float) Set

        func (z *Float) Set(x *Float) *Float

        Set sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to the precision of x before setting z (and rounding will have no effect). Rounding is performed according to z's precision and rounding mode; and z's accuracy reports the result error relative to the exact (not rounded) result.

        func (*Float) SetFloat64

        func (z *Float) SetFloat64(x float64) *Float

        SetFloat64 sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to 53 (and rounding will have no effect). SetFloat64 panics with ErrNaN if x is a NaN.

        func (*Float) SetInf

        func (z *Float) SetInf(signbit bool) *Float

        SetInf sets z to the infinite Float -Inf if signbit is set, or +Inf if signbit is not set, and returns z. The precision of z is unchanged and the result is always Exact.

        func (*Float) SetInt

        func (z *Float) SetInt(x *Int) *Float

        SetInt sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to the larger of x.BitLen() or 64 (and rounding will have no effect).

        func (*Float) SetInt64

        func (z *Float) SetInt64(x int64) *Float

        SetInt64 sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to 64 (and rounding will have no effect).

        func (*Float) SetMantExp

        func (z *Float) SetMantExp(mant *Float, exp int) *Float

        SetMantExp sets z to mant × 2**exp and returns z. The result z has the same precision and rounding mode as mant. SetMantExp is an inverse of Float.MantExp but does not require 0.5 <= |mant| < 1.0. Specifically, for a given x of type *Float, SetMantExp relates to Float.MantExp as follows:

        mant := new(Float)
        new(Float).SetMantExp(mant, x.MantExp(mant)).Cmp(x) == 0
        

        Special cases are:

        z.SetMantExp(  ±0, exp) =   ±0
        z.SetMantExp(±Inf, exp) = ±Inf
        

        z and mant may be the same in which case z's exponent is set to exp.

        func (*Float) SetMode

        func (z *Float) SetMode(mode RoundingMode) *Float

        SetMode sets z's rounding mode to mode and returns an exact z. z remains unchanged otherwise. z.SetMode(z.Mode()) is a cheap way to set z's accuracy to Exact.

        func (*Float) SetPrec

        func (z *Float) SetPrec(prec uint) *Float

        SetPrec sets z's precision to prec and returns the (possibly) rounded value of z. Rounding occurs according to z's rounding mode if the mantissa cannot be represented in prec bits without loss of precision. SetPrec(0) maps all finite values to ±0; infinite values remain unchanged. If prec > MaxPrec, it is set to MaxPrec.

        func (*Float) SetRat

        func (z *Float) SetRat(x *Rat) *Float

        SetRat sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to the largest of a.BitLen(), b.BitLen(), or 64; with x = a/b.

        func (*Float) SetString

        func (z *Float) SetString(s string) (*Float, bool)

        SetString sets z to the value of s and returns z and a boolean indicating success. s must be a floating-point number of the same format as accepted by Float.Parse, with base argument 0. The entire string (not just a prefix) must be valid for success. If the operation failed, the value of z is undefined but the returned value is nil.

        Example

        Code:

        f := new(big.Float)
        f.SetString("3.14159")
        fmt.Println(f)
        

        Output:

        3.14159
        

        func (*Float) SetUint64

        func (z *Float) SetUint64(x uint64) *Float

        SetUint64 sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to 64 (and rounding will have no effect).

        func (*Float) Sign

        func (x *Float) Sign() int

        Sign returns:

        -1 if x <   0
         0 if x is ±0
        +1 if x >   0
        

        func (*Float) Signbit

        func (x *Float) Signbit() bool

        Signbit reports whether x is negative or negative zero.

        func (*Float) Sqrt

        func (z *Float) Sqrt(x *Float) *Float

        Sqrt sets z to the rounded square root of x, and returns it.

        If z's precision is 0, it is changed to x's precision before the operation. Rounding is performed according to z's precision and rounding mode, but z's accuracy is not computed. Specifically, the result of z.Acc() is undefined.

        The function panics if z < 0. The value of z is undefined in that case.

        func (*Float) String

        func (x *Float) String() string

        String formats x like x.Text('g', 10). (String must be called explicitly, Float.Format does not support %s verb.)

        func (*Float) Sub

        func (z *Float) Sub(x, y *Float) *Float

        Sub sets z to the rounded difference x-y and returns z. Precision, rounding, and accuracy reporting are as for Float.Add. Sub panics with ErrNaN if x and y are infinities with equal signs. The value of z is undefined in that case.

        func (*Float) Text

        func (x *Float) Text(format byte, prec int) string

        Text converts the floating-point number x to a string according to the given format and precision prec. The format is one of:

        'e'	-d.dddde±dd, decimal exponent, at least two (possibly 0) exponent digits
        'E'	-d.ddddE±dd, decimal exponent, at least two (possibly 0) exponent digits
        'f'	-ddddd.dddd, no exponent
        'g'	like 'e' for large exponents, like 'f' otherwise
        'G'	like 'E' for large exponents, like 'f' otherwise
        'x'	-0xd.dddddp±dd, hexadecimal mantissa, decimal power of two exponent
        'p'	-0x.dddp±dd, hexadecimal mantissa, decimal power of two exponent (non-standard)
        'b'	-ddddddp±dd, decimal mantissa, decimal power of two exponent (non-standard)
        

        For the power-of-two exponent formats, the mantissa is printed in normalized form:

        'x'	hexadecimal mantissa in [1, 2), or 0
        'p'	hexadecimal mantissa in [½, 1), or 0
        'b'	decimal integer mantissa using x.Prec() bits, or 0
        

        Note that the 'x' form is the one used by most other languages and libraries.

        If format is a different character, Text returns a "%" followed by the unrecognized format character.

        The precision prec controls the number of digits (excluding the exponent) printed by the 'e', 'E', 'f', 'g', 'G', and 'x' formats. For 'e', 'E', 'f', and 'x', it is the number of digits after the decimal point. For 'g' and 'G' it is the total number of digits. A negative precision selects the smallest number of decimal digits necessary to identify the value x uniquely using x.Prec() mantissa bits. The prec value is ignored for the 'b' and 'p' formats.

        func (*Float) Uint64

        func (x *Float) Uint64() (uint64, Accuracy)

        Uint64 returns the unsigned integer resulting from truncating x towards zero. If 0 <= x <= math.MaxUint64, the result is Exact if x is an integer and Below otherwise. The result is (0, Above) for x < 0, and (math.MaxUint64, Below) for x > math.MaxUint64.

        func (*Float) UnmarshalText

        func (z *Float) UnmarshalText(text []byte) error

        UnmarshalText implements the encoding.TextUnmarshaler interface. The result is rounded per the precision and rounding mode of z. If z's precision is 0, it is changed to 64 before rounding takes effect.

        type Int

        An Int represents a signed multi-precision integer. The zero value for an Int represents the value 0.

        Operations always take pointer arguments (*Int) rather than Int values, and each unique Int value requires its own unique *Int pointer. To "copy" an Int value, an existing (or newly allocated) Int must be set to a new value using the Int.Set method; shallow copies of Ints are not supported and may lead to errors.

        Note that methods may leak the Int's value through timing side-channels. Because of this and because of the scope and complexity of the implementation, Int is not well-suited to implement cryptographic operations. The standard library avoids exposing non-trivial Int methods to attacker-controlled inputs and the determination of whether a bug in math/big is considered a security vulnerability might depend on the impact on the standard library.

        type Int struct {
            // contains filtered or unexported fields
        }
        

        func NewInt

        func NewInt(x int64) *Int

        NewInt allocates and returns a new Int set to x.

        func (*Int) Abs

        func (z *Int) Abs(x *Int) *Int

        Abs sets z to |x| (the absolute value of x) and returns z.

        func (*Int) Add

        func (z *Int) Add(x, y *Int) *Int

        Add sets z to the sum x+y and returns z.

        func (*Int) And

        func (z *Int) And(x, y *Int) *Int

        And sets z = x & y and returns z.

        func (*Int) AndNot

        func (z *Int) AndNot(x, y *Int) *Int

        AndNot sets z = x &^ y and returns z.

        func (*Int) Append

        func (x *Int) Append(buf []byte, base int) []byte

        Append appends the string representation of x, as generated by x.Text(base), to buf and returns the extended buffer.

        func (*Int) Binomial

        func (z *Int) Binomial(n, k int64) *Int

        Binomial sets z to the binomial coefficient C(n, k) and returns z.

        func (*Int) Bit

        func (x *Int) Bit(i int) uint

        Bit returns the value of the i'th bit of x. That is, it returns (x>>i)&1. The bit index i must be >= 0.

        func (*Int) BitLen

        func (x *Int) BitLen() int

        BitLen returns the length of the absolute value of x in bits. The bit length of 0 is 0.

        func (*Int) Bits

        func (x *Int) Bits() []Word

        Bits provides raw (unchecked but fast) access to x by returning its absolute value as a little-endian Word slice. The result and x share the same underlying array. Bits is intended to support implementation of missing low-level Int functionality outside this package; it should be avoided otherwise.

        func (*Int) Bytes

        func (x *Int) Bytes() []byte

        Bytes returns the absolute value of x as a big-endian byte slice.

        To use a fixed length slice, or a preallocated one, use Int.FillBytes.

        func (*Int) Cmp

        func (x *Int) Cmp(y *Int) (r int)

        Cmp compares x and y and returns:

        -1 if x <  y
         0 if x == y
        +1 if x >  y
        

        func (*Int) CmpAbs

        func (x *Int) CmpAbs(y *Int) int

        CmpAbs compares the absolute values of x and y and returns:

        -1 if |x| <  |y|
         0 if |x| == |y|
        +1 if |x| >  |y|
        

        func (*Int) Div

        func (z *Int) Div(x, y *Int) *Int

        Div sets z to the quotient x/y for y != 0 and returns z. If y == 0, a division-by-zero run-time panic occurs. Div implements Euclidean division (unlike Go); see Int.DivMod for more details.

        func (*Int) DivMod

        func (z *Int) DivMod(x, y, m *Int) (*Int, *Int)

        DivMod sets z to the quotient x div y and m to the modulus x mod y and returns the pair (z, m) for y != 0. If y == 0, a division-by-zero run-time panic occurs.

        DivMod implements Euclidean division and modulus (unlike Go):

        q = x div y  such that
        m = x - y*q  with 0 <= m < |y|
        

        (See Raymond T. Boute, “The Euclidean definition of the functions div and mod”. ACM Transactions on Programming Languages and Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992. ACM press.) See Int.QuoRem for T-division and modulus (like Go).

        func (*Int) Exp

        func (z *Int) Exp(x, y, m *Int) *Int

        Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z. If m == nil or m == 0, z = x**y unless y <= 0 then z = 1. If m != 0, y < 0, and x and m are not relatively prime, z is unchanged and nil is returned.

        Modular exponentiation of inputs of a particular size is not a cryptographically constant-time operation.

        func (*Int) FillBytes

        func (x *Int) FillBytes(buf []byte) []byte

        FillBytes sets buf to the absolute value of x, storing it as a zero-extended big-endian byte slice, and returns buf.

        If the absolute value of x doesn't fit in buf, FillBytes will panic.

        func (*Int) Float64

        func (x *Int) Float64() (float64, Accuracy)

        Float64 returns the float64 value nearest x, and an indication of any rounding that occurred.

        func (*Int) Format

        func (x *Int) Format(s fmt.State, ch rune)

        Format implements fmt.Formatter. It accepts the formats 'b' (binary), 'o' (octal with 0 prefix), 'O' (octal with 0o prefix), 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal). Also supported are the full suite of package fmt's format flags for integral types, including '+' and ' ' for sign control, '#' for leading zero in octal and for hexadecimal, a leading "0x" or "0X" for "%#x" and "%#X" respectively, specification of minimum digits precision, output field width, space or zero padding, and '-' for left or right justification.

        func (*Int) GCD

        func (z *Int) GCD(x, y, a, b *Int) *Int

        GCD sets z to the greatest common divisor of a and b and returns z. If x or y are not nil, GCD sets their value such that z = a*x + b*y.

        a and b may be positive, zero or negative. (Before Go 1.14 both had to be > 0.) Regardless of the signs of a and b, z is always >= 0.

        If a == b == 0, GCD sets z = x = y = 0.

        If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1.

        If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0.

        func (*Int) GobDecode

        func (z *Int) GobDecode(buf []byte) error

        GobDecode implements the encoding/gob.GobDecoder interface.

        func (*Int) GobEncode

        func (x *Int) GobEncode() ([]byte, error)

        GobEncode implements the encoding/gob.GobEncoder interface.

        func (*Int) Int64

        func (x *Int) Int64() int64

        Int64 returns the int64 representation of x. If x cannot be represented in an int64, the result is undefined.

        func (*Int) IsInt64

        func (x *Int) IsInt64() bool

        IsInt64 reports whether x can be represented as an int64.

        func (*Int) IsUint64

        func (x *Int) IsUint64() bool

        IsUint64 reports whether x can be represented as a uint64.

        func (*Int) Lsh

        func (z *Int) Lsh(x *Int, n uint) *Int

        Lsh sets z = x << n and returns z.

        func (*Int) MarshalJSON

        func (x *Int) MarshalJSON() ([]byte, error)

        MarshalJSON implements the encoding/json.Marshaler interface.

        func (*Int) MarshalText

        func (x *Int) MarshalText() (text []byte, err error)

        MarshalText implements the encoding.TextMarshaler interface.

        func (*Int) Mod

        func (z *Int) Mod(x, y *Int) *Int

        Mod sets z to the modulus x%y for y != 0 and returns z. If y == 0, a division-by-zero run-time panic occurs. Mod implements Euclidean modulus (unlike Go); see Int.DivMod for more details.

        func (*Int) ModInverse

        func (z *Int) ModInverse(g, n *Int) *Int

        ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ and returns z. If g and n are not relatively prime, g has no multiplicative inverse in the ring ℤ/nℤ. In this case, z is unchanged and the return value is nil. If n == 0, a division-by-zero run-time panic occurs.

        func (*Int) ModSqrt

        func (z *Int) ModSqrt(x, p *Int) *Int

        ModSqrt sets z to a square root of x mod p if such a square root exists, and returns z. The modulus p must be an odd prime. If x is not a square mod p, ModSqrt leaves z unchanged and returns nil. This function panics if p is not an odd integer, its behavior is undefined if p is odd but not prime.

        func (*Int) Mul

        func (z *Int) Mul(x, y *Int) *Int

        Mul sets z to the product x*y and returns z.

        func (*Int) MulRange

        func (z *Int) MulRange(a, b int64) *Int

        MulRange sets z to the product of all integers in the range [a, b] inclusively and returns z. If a > b (empty range), the result is 1.

        func (*Int) Neg

        func (z *Int) Neg(x *Int) *Int

        Neg sets z to -x and returns z.

        func (*Int) Not

        func (z *Int) Not(x *Int) *Int

        Not sets z = ^x and returns z.

        func (*Int) Or

        func (z *Int) Or(x, y *Int) *Int

        Or sets z = x | y and returns z.

        func (*Int) ProbablyPrime

        func (x *Int) ProbablyPrime(n int) bool

        ProbablyPrime reports whether x is probably prime, applying the Miller-Rabin test with n pseudorandomly chosen bases as well as a Baillie-PSW test.

        If x is prime, ProbablyPrime returns true. If x is chosen randomly and not prime, ProbablyPrime probably returns false. The probability of returning true for a randomly chosen non-prime is at most ¼ⁿ.

        ProbablyPrime is 100% accurate for inputs less than 2⁶⁴. See Menezes et al., Handbook of Applied Cryptography, 1997, pp. 145-149, and FIPS 186-4 Appendix F for further discussion of the error probabilities.

        ProbablyPrime is not suitable for judging primes that an adversary may have crafted to fool the test.

        As of Go 1.8, ProbablyPrime(0) is allowed and applies only a Baillie-PSW test. Before Go 1.8, ProbablyPrime applied only the Miller-Rabin tests, and ProbablyPrime(0) panicked.

        func (*Int) Quo

        func (z *Int) Quo(x, y *Int) *Int

        Quo sets z to the quotient x/y for y != 0 and returns z. If y == 0, a division-by-zero run-time panic occurs. Quo implements truncated division (like Go); see Int.QuoRem for more details.

        func (*Int) QuoRem

        func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int)

        QuoRem sets z to the quotient x/y and r to the remainder x%y and returns the pair (z, r) for y != 0. If y == 0, a division-by-zero run-time panic occurs.

        QuoRem implements T-division and modulus (like Go):

        q = x/y      with the result truncated to zero
        r = x - y*q
        

        (See Daan Leijen, “Division and Modulus for Computer Scientists”.) See DivMod for Euclidean division and modulus (unlike Go).

        func (*Int) Rand

        func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int

        Rand sets z to a pseudo-random number in [0, n) and returns z.

        As this uses the math/rand package, it must not be used for security-sensitive work. Use crypto/rand.Int instead.

        func (*Int) Rem

        func (z *Int) Rem(x, y *Int) *Int

        Rem sets z to the remainder x%y for y != 0 and returns z. If y == 0, a division-by-zero run-time panic occurs. Rem implements truncated modulus (like Go); see Int.QuoRem for more details.

        func (*Int) Rsh

        func (z *Int) Rsh(x *Int, n uint) *Int

        Rsh sets z = x >> n and returns z.

        func (*Int) Scan

        func (z *Int) Scan(s fmt.ScanState, ch rune) error

        Scan is a support routine for fmt.Scanner; it sets z to the value of the scanned number. It accepts the formats 'b' (binary), 'o' (octal), 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal).

        Example

        Code:

        // The Scan function is rarely used directly;
        // the fmt package recognizes it as an implementation of fmt.Scanner.
        i := new(big.Int)
        _, err := fmt.Sscan("18446744073709551617", i)
        if err != nil {
            log.Println("error scanning value:", err)
        } else {
            fmt.Println(i)
        }
        

        Output:

        18446744073709551617
        

        func (*Int) Set

        func (z *Int) Set(x *Int) *Int

        Set sets z to x and returns z.

        func (*Int) SetBit

        func (z *Int) SetBit(x *Int, i int, b uint) *Int

        SetBit sets z to x, with x's i'th bit set to b (0 or 1). That is, if b is 1 SetBit sets z = x | (1 << i); if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1, SetBit will panic.

        func (*Int) SetBits

        func (z *Int) SetBits(abs []Word) *Int

        SetBits provides raw (unchecked but fast) access to z by setting its value to abs, interpreted as a little-endian Word slice, and returning z. The result and abs share the same underlying array. SetBits is intended to support implementation of missing low-level Int functionality outside this package; it should be avoided otherwise.

        func (*Int) SetBytes

        func (z *Int) SetBytes(buf []byte) *Int

        SetBytes interprets buf as the bytes of a big-endian unsigned integer, sets z to that value, and returns z.

        func (*Int) SetInt64

        func (z *Int) SetInt64(x int64) *Int

        SetInt64 sets z to x and returns z.

        func (*Int) SetString

        func (z *Int) SetString(s string, base int) (*Int, bool)

        SetString sets z to the value of s, interpreted in the given base, and returns z and a boolean indicating success. The entire string (not just a prefix) must be valid for success. If SetString fails, the value of z is undefined but the returned value is nil.

        The base argument must be 0 or a value between 2 and MaxBase. For base 0, the number prefix determines the actual base: A prefix of “0b” or “0B” selects base 2, “0”, “0o” or “0O” selects base 8, and “0x” or “0X” selects base 16. Otherwise, the selected base is 10 and no prefix is accepted.

        For bases <= 36, lower and upper case letters are considered the same: The letters 'a' to 'z' and 'A' to 'Z' represent digit values 10 to 35. For bases > 36, the upper case letters 'A' to 'Z' represent the digit values 36 to 61.

        For base 0, an underscore character “_” may appear between a base prefix and an adjacent digit, and between successive digits; such underscores do not change the value of the number. Incorrect placement of underscores is reported as an error if there are no other errors. If base != 0, underscores are not recognized and act like any other character that is not a valid digit.

        Example

        Code:

        i := new(big.Int)
        i.SetString("644", 8) // octal
        fmt.Println(i)
        

        Output:

        420
        

        func (*Int) SetUint64

        func (z *Int) SetUint64(x uint64) *Int

        SetUint64 sets z to x and returns z.

        func (*Int) Sign

        func (x *Int) Sign() int

        Sign returns:

        -1 if x <  0
         0 if x == 0
        +1 if x >  0
        

        func (*Int) Sqrt

        func (z *Int) Sqrt(x *Int) *Int

        Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z. It panics if x is negative.

        func (*Int) String

        func (x *Int) String() string

        String returns the decimal representation of x as generated by x.Text(10).

        func (*Int) Sub

        func (z *Int) Sub(x, y *Int) *Int

        Sub sets z to the difference x-y and returns z.

        func (*Int) Text

        func (x *Int) Text(base int) string

        Text returns the string representation of x in the given base. Base must be between 2 and 62, inclusive. The result uses the lower-case letters 'a' to 'z' for digit values 10 to 35, and the upper-case letters 'A' to 'Z' for digit values 36 to 61. No prefix (such as "0x") is added to the string. If x is a nil pointer it returns "<nil>".

        func (*Int) TrailingZeroBits

        func (x *Int) TrailingZeroBits() uint

        TrailingZeroBits returns the number of consecutive least significant zero bits of |x|.

        func (*Int) Uint64

        func (x *Int) Uint64() uint64

        Uint64 returns the uint64 representation of x. If x cannot be represented in a uint64, the result is undefined.

        func (*Int) UnmarshalJSON

        func (z *Int) UnmarshalJSON(text []byte) error

        UnmarshalJSON implements the encoding/json.Unmarshaler interface.

        func (*Int) UnmarshalText

        func (z *Int) UnmarshalText(text []byte) error

        UnmarshalText implements the encoding.TextUnmarshaler interface.

        func (*Int) Xor

        func (z *Int) Xor(x, y *Int) *Int

        Xor sets z = x ^ y and returns z.

        type Rat

        A Rat represents a quotient a/b of arbitrary precision. The zero value for a Rat represents the value 0.

        Operations always take pointer arguments (*Rat) rather than Rat values, and each unique Rat value requires its own unique *Rat pointer. To "copy" a Rat value, an existing (or newly allocated) Rat must be set to a new value using the Rat.Set method; shallow copies of Rats are not supported and may lead to errors.

        type Rat struct {
            // contains filtered or unexported fields
        }
        

        func NewRat

        func NewRat(a, b int64) *Rat

        NewRat creates a new Rat with numerator a and denominator b.

        func (*Rat) Abs

        func (z *Rat) Abs(x *Rat) *Rat

        Abs sets z to |x| (the absolute value of x) and returns z.

        func (*Rat) Add

        func (z *Rat) Add(x, y *Rat) *Rat

        Add sets z to the sum x+y and returns z.

        func (*Rat) Cmp

        func (x *Rat) Cmp(y *Rat) int

        Cmp compares x and y and returns:

        -1 if x <  y
         0 if x == y
        +1 if x >  y
        

        func (*Rat) Denom

        func (x *Rat) Denom() *Int

        Denom returns the denominator of x; it is always > 0. The result is a reference to x's denominator, unless x is an uninitialized (zero value) Rat, in which case the result is a new Int of value 1. (To initialize x, any operation that sets x will do, including x.Set(x).) If the result is a reference to x's denominator it may change if a new value is assigned to x, and vice versa.

        func (*Rat) Float32

        func (x *Rat) Float32() (f float32, exact bool)

        Float32 returns the nearest float32 value for x and a bool indicating whether f represents x exactly. If the magnitude of x is too large to be represented by a float32, f is an infinity and exact is false. The sign of f always matches the sign of x, even if f == 0.

        func (*Rat) Float64

        func (x *Rat) Float64() (f float64, exact bool)

        Float64 returns the nearest float64 value for x and a bool indicating whether f represents x exactly. If the magnitude of x is too large to be represented by a float64, f is an infinity and exact is false. The sign of f always matches the sign of x, even if f == 0.

        func (*Rat) FloatPrec

        func (x *Rat) FloatPrec() (n int, exact bool)

        FloatPrec returns the number n of non-repeating digits immediately following the decimal point of the decimal representation of x. The boolean result indicates whether a decimal representation of x with that many fractional digits is exact or rounded.

        Examples:

        x      n    exact    decimal representation n fractional digits
        0      0    true     0
        1      0    true     1
        1/2    1    true     0.5
        1/3    0    false    0       (0.333... rounded)
        1/4    2    true     0.25
        1/6    1    false    0.2     (0.166... rounded)
        

        func (*Rat) FloatString

        func (x *Rat) FloatString(prec int) string

        FloatString returns a string representation of x in decimal form with prec digits of precision after the radix point. The last digit is rounded to nearest, with halves rounded away from zero.

        func (*Rat) GobDecode

        func (z *Rat) GobDecode(buf []byte) error

        GobDecode implements the encoding/gob.GobDecoder interface.

        func (*Rat) GobEncode

        func (x *Rat) GobEncode() ([]byte, error)

        GobEncode implements the encoding/gob.GobEncoder interface.

        func (*Rat) Inv

        func (z *Rat) Inv(x *Rat) *Rat

        Inv sets z to 1/x and returns z. If x == 0, Inv panics.

        func (*Rat) IsInt

        func (x *Rat) IsInt() bool

        IsInt reports whether the denominator of x is 1.

        func (*Rat) MarshalText

        func (x *Rat) MarshalText() (text []byte, err error)

        MarshalText implements the encoding.TextMarshaler interface.

        func (*Rat) Mul

        func (z *Rat) Mul(x, y *Rat) *Rat

        Mul sets z to the product x*y and returns z.

        func (*Rat) Neg

        func (z *Rat) Neg(x *Rat) *Rat

        Neg sets z to -x and returns z.

        func (*Rat) Num

        func (x *Rat) Num() *Int

        Num returns the numerator of x; it may be <= 0. The result is a reference to x's numerator; it may change if a new value is assigned to x, and vice versa. The sign of the numerator corresponds to the sign of x.

        func (*Rat) Quo

        func (z *Rat) Quo(x, y *Rat) *Rat

        Quo sets z to the quotient x/y and returns z. If y == 0, Quo panics.

        func (*Rat) RatString

        func (x *Rat) RatString() string

        RatString returns a string representation of x in the form "a/b" if b != 1, and in the form "a" if b == 1.

        func (*Rat) Scan

        func (z *Rat) Scan(s fmt.ScanState, ch rune) error

        Scan is a support routine for fmt.Scanner. It accepts the formats 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent.

        Example

        Code:

        // The Scan function is rarely used directly;
        // the fmt package recognizes it as an implementation of fmt.Scanner.
        r := new(big.Rat)
        _, err := fmt.Sscan("1.5000", r)
        if err != nil {
            log.Println("error scanning value:", err)
        } else {
            fmt.Println(r)
        }
        

        Output:

        3/2
        

        func (*Rat) Set

        func (z *Rat) Set(x *Rat) *Rat

        Set sets z to x (by making a copy of x) and returns z.

        func (*Rat) SetFloat64

        func (z *Rat) SetFloat64(f float64) *Rat

        SetFloat64 sets z to exactly f and returns z. If f is not finite, SetFloat returns nil.

        func (*Rat) SetFrac

        func (z *Rat) SetFrac(a, b *Int) *Rat

        SetFrac sets z to a/b and returns z. If b == 0, SetFrac panics.

        func (*Rat) SetFrac64

        func (z *Rat) SetFrac64(a, b int64) *Rat

        SetFrac64 sets z to a/b and returns z. If b == 0, SetFrac64 panics.

        func (*Rat) SetInt

        func (z *Rat) SetInt(x *Int) *Rat

        SetInt sets z to x (by making a copy of x) and returns z.

        func (*Rat) SetInt64

        func (z *Rat) SetInt64(x int64) *Rat

        SetInt64 sets z to x and returns z.

        func (*Rat) SetString

        func (z *Rat) SetString(s string) (*Rat, bool)

        SetString sets z to the value of s and returns z and a boolean indicating success. s can be given as a (possibly signed) fraction "a/b", or as a floating-point number optionally followed by an exponent. If a fraction is provided, both the dividend and the divisor may be a decimal integer or independently use a prefix of “0b”, “0” or “0o”, or “0x” (or their upper-case variants) to denote a binary, octal, or hexadecimal integer, respectively. The divisor may not be signed. If a floating-point number is provided, it may be in decimal form or use any of the same prefixes as above but for “0” to denote a non-decimal mantissa. A leading “0” is considered a decimal leading 0; it does not indicate octal representation in this case. An optional base-10 “e” or base-2 “p” (or their upper-case variants) exponent may be provided as well, except for hexadecimal floats which only accept an (optional) “p” exponent (because an “e” or “E” cannot be distinguished from a mantissa digit). If the exponent's absolute value is too large, the operation may fail. The entire string, not just a prefix, must be valid for success. If the operation failed, the value of z is undefined but the returned value is nil.

        Example

        Code:

        r := new(big.Rat)
        r.SetString("355/113")
        fmt.Println(r.FloatString(3))
        

        Output:

        3.142
        

        func (*Rat) SetUint64

        func (z *Rat) SetUint64(x uint64) *Rat

        SetUint64 sets z to x and returns z.

        func (*Rat) Sign

        func (x *Rat) Sign() int

        Sign returns:

        -1 if x <  0
         0 if x == 0
        +1 if x >  0
        

        func (*Rat) String

        func (x *Rat) String() string

        String returns a string representation of x in the form "a/b" (even if b == 1).

        func (*Rat) Sub

        func (z *Rat) Sub(x, y *Rat) *Rat

        Sub sets z to the difference x-y and returns z.

        func (*Rat) UnmarshalText

        func (z *Rat) UnmarshalText(text []byte) error

        UnmarshalText implements the encoding.TextUnmarshaler interface.

        type RoundingMode

        RoundingMode determines how a Float value is rounded to the desired precision. Rounding may change the Float value; the rounding error is described by the Float's Accuracy.

        type RoundingMode byte

        These constants define supported rounding modes.

        const (
            ToNearestEven RoundingMode = iota // == IEEE 754-2008 roundTiesToEven
            ToNearestAway                     // == IEEE 754-2008 roundTiesToAway
            ToZero                            // == IEEE 754-2008 roundTowardZero
            AwayFromZero                      // no IEEE 754-2008 equivalent
            ToNegativeInf                     // == IEEE 754-2008 roundTowardNegative
            ToPositiveInf                     // == IEEE 754-2008 roundTowardPositive
        )

        Example

        Code:

        operands := []float64{2.6, 2.5, 2.1, -2.1, -2.5, -2.6}
        
        fmt.Print("   x")
        for mode := big.ToNearestEven; mode <= big.ToPositiveInf; mode++ {
            fmt.Printf("  %s", mode)
        }
        fmt.Println()
        
        for _, f64 := range operands {
            fmt.Printf("%4g", f64)
            for mode := big.ToNearestEven; mode <= big.ToPositiveInf; mode++ {
                // sample operands above require 2 bits to represent mantissa
                // set binary precision to 2 to round them to integer values
                f := new(big.Float).SetPrec(2).SetMode(mode).SetFloat64(f64)
                fmt.Printf("  %*g", len(mode.String()), f)
            }
            fmt.Println()
        }
        
        

        Output:

           x  ToNearestEven  ToNearestAway  ToZero  AwayFromZero  ToNegativeInf  ToPositiveInf
         2.6              3              3       2             3              2              3
         2.5              2              3       2             3              2              3
         2.1              2              2       2             3              2              3
        -2.1             -2             -2      -2            -3             -3             -2
        -2.5             -2             -3      -2            -3             -3             -2
        -2.6             -3             -3      -2            -3             -3             -2
        

        func (RoundingMode) String

        func (i RoundingMode) String() string

        type Word

        A Word represents a single digit of a multi-precision unsigned integer.

        type Word uint
        bits - Go Documentation Server
        ...

        Package bits

        import "math/bits"
        Overview
        Index
        Examples

        Overview ▾

        Package bits implements bit counting and manipulation functions for the predeclared unsigned integer types.

        Functions in this package may be implemented directly by the compiler, for better performance. For those functions the code in this package will not be used. Which functions are implemented by the compiler depends on the architecture and the Go release.

        Index ▾

        Constants
        func Add(x, y, carry uint) (sum, carryOut uint)
        func Add32(x, y, carry uint32) (sum, carryOut uint32)
        func Add64(x, y, carry uint64) (sum, carryOut uint64)
        func Div(hi, lo, y uint) (quo, rem uint)
        func Div32(hi, lo, y uint32) (quo, rem uint32)
        func Div64(hi, lo, y uint64) (quo, rem uint64)
        func LeadingZeros(x uint) int
        func LeadingZeros16(x uint16) int
        func LeadingZeros32(x uint32) int
        func LeadingZeros64(x uint64) int
        func LeadingZeros8(x uint8) int
        func Len(x uint) int
        func Len16(x uint16) (n int)
        func Len32(x uint32) (n int)
        func Len64(x uint64) (n int)
        func Len8(x uint8) int
        func Mul(x, y uint) (hi, lo uint)
        func Mul32(x, y uint32) (hi, lo uint32)
        func Mul64(x, y uint64) (hi, lo uint64)
        func OnesCount(x uint) int
        func OnesCount16(x uint16) int
        func OnesCount32(x uint32) int
        func OnesCount64(x uint64) int
        func OnesCount8(x uint8) int
        func Rem(hi, lo, y uint) uint
        func Rem32(hi, lo, y uint32) uint32
        func Rem64(hi, lo, y uint64) uint64
        func Reverse(x uint) uint
        func Reverse16(x uint16) uint16
        func Reverse32(x uint32) uint32
        func Reverse64(x uint64) uint64
        func Reverse8(x uint8) uint8
        func ReverseBytes(x uint) uint
        func ReverseBytes16(x uint16) uint16
        func ReverseBytes32(x uint32) uint32
        func ReverseBytes64(x uint64) uint64
        func RotateLeft(x uint, k int) uint
        func RotateLeft16(x uint16, k int) uint16
        func RotateLeft32(x uint32, k int) uint32
        func RotateLeft64(x uint64, k int) uint64
        func RotateLeft8(x uint8, k int) uint8
        func Sub(x, y, borrow uint) (diff, borrowOut uint)
        func Sub32(x, y, borrow uint32) (diff, borrowOut uint32)
        func Sub64(x, y, borrow uint64) (diff, borrowOut uint64)
        func TrailingZeros(x uint) int
        func TrailingZeros16(x uint16) int
        func TrailingZeros32(x uint32) int
        func TrailingZeros64(x uint64) int
        func TrailingZeros8(x uint8) int

        Package files

        bits.go bits_errors.go bits_tables.go

        Constants

        UintSize is the size of a uint in bits.

        const UintSize = uintSize

        func Add

        func Add(x, y, carry uint) (sum, carryOut uint)

        Add returns the sum with carry of x, y and carry: sum = x + y + carry. The carry input must be 0 or 1; otherwise the behavior is undefined. The carryOut output is guaranteed to be 0 or 1.

        This function's execution time does not depend on the inputs.

        func Add32

        func Add32(x, y, carry uint32) (sum, carryOut uint32)

        Add32 returns the sum with carry of x, y and carry: sum = x + y + carry. The carry input must be 0 or 1; otherwise the behavior is undefined. The carryOut output is guaranteed to be 0 or 1.

        This function's execution time does not depend on the inputs.

        Example

        Code:

        // First number is 33<<32 + 12
        n1 := []uint32{33, 12}
        // Second number is 21<<32 + 23
        n2 := []uint32{21, 23}
        // Add them together without producing carry.
        d1, carry := bits.Add32(n1[1], n2[1], 0)
        d0, _ := bits.Add32(n1[0], n2[0], carry)
        nsum := []uint32{d0, d1}
        fmt.Printf("%v + %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
        
        // First number is 1<<32 + 2147483648
        n1 = []uint32{1, 0x80000000}
        // Second number is 1<<32 + 2147483648
        n2 = []uint32{1, 0x80000000}
        // Add them together producing carry.
        d1, carry = bits.Add32(n1[1], n2[1], 0)
        d0, _ = bits.Add32(n1[0], n2[0], carry)
        nsum = []uint32{d0, d1}
        fmt.Printf("%v + %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
        

        Output:

        [33 12] + [21 23] = [54 35] (carry bit was 0)
        [1 2147483648] + [1 2147483648] = [3 0] (carry bit was 1)
        

        func Add64

        func Add64(x, y, carry uint64) (sum, carryOut uint64)

        Add64 returns the sum with carry of x, y and carry: sum = x + y + carry. The carry input must be 0 or 1; otherwise the behavior is undefined. The carryOut output is guaranteed to be 0 or 1.

        This function's execution time does not depend on the inputs.

        Example

        Code:

        // First number is 33<<64 + 12
        n1 := []uint64{33, 12}
        // Second number is 21<<64 + 23
        n2 := []uint64{21, 23}
        // Add them together without producing carry.
        d1, carry := bits.Add64(n1[1], n2[1], 0)
        d0, _ := bits.Add64(n1[0], n2[0], carry)
        nsum := []uint64{d0, d1}
        fmt.Printf("%v + %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
        
        // First number is 1<<64 + 9223372036854775808
        n1 = []uint64{1, 0x8000000000000000}
        // Second number is 1<<64 + 9223372036854775808
        n2 = []uint64{1, 0x8000000000000000}
        // Add them together producing carry.
        d1, carry = bits.Add64(n1[1], n2[1], 0)
        d0, _ = bits.Add64(n1[0], n2[0], carry)
        nsum = []uint64{d0, d1}
        fmt.Printf("%v + %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
        

        Output:

        [33 12] + [21 23] = [54 35] (carry bit was 0)
        [1 9223372036854775808] + [1 9223372036854775808] = [3 0] (carry bit was 1)
        

        func Div

        func Div(hi, lo, y uint) (quo, rem uint)

        Div returns the quotient and remainder of (hi, lo) divided by y: quo = (hi, lo)/y, rem = (hi, lo)%y with the dividend bits' upper half in parameter hi and the lower half in parameter lo. Div panics for y == 0 (division by zero) or y <= hi (quotient overflow).

        func Div32

        func Div32(hi, lo, y uint32) (quo, rem uint32)

        Div32 returns the quotient and remainder of (hi, lo) divided by y: quo = (hi, lo)/y, rem = (hi, lo)%y with the dividend bits' upper half in parameter hi and the lower half in parameter lo. Div32 panics for y == 0 (division by zero) or y <= hi (quotient overflow).

        Example

        Code:

        // First number is 0<<32 + 6
        n1 := []uint32{0, 6}
        // Second number is 0<<32 + 3
        n2 := []uint32{0, 3}
        // Divide them together.
        quo, rem := bits.Div32(n1[0], n1[1], n2[1])
        nsum := []uint32{quo, rem}
        fmt.Printf("[%v %v] / %v = %v\n", n1[0], n1[1], n2[1], nsum)
        
        // First number is 2<<32 + 2147483648
        n1 = []uint32{2, 0x80000000}
        // Second number is 0<<32 + 2147483648
        n2 = []uint32{0, 0x80000000}
        // Divide them together.
        quo, rem = bits.Div32(n1[0], n1[1], n2[1])
        nsum = []uint32{quo, rem}
        fmt.Printf("[%v %v] / %v = %v\n", n1[0], n1[1], n2[1], nsum)
        

        Output:

        [0 6] / 3 = [2 0]
        [2 2147483648] / 2147483648 = [5 0]
        

        func Div64

        func Div64(hi, lo, y uint64) (quo, rem uint64)

        Div64 returns the quotient and remainder of (hi, lo) divided by y: quo = (hi, lo)/y, rem = (hi, lo)%y with the dividend bits' upper half in parameter hi and the lower half in parameter lo. Div64 panics for y == 0 (division by zero) or y <= hi (quotient overflow).

        Example

        Code:

        // First number is 0<<64 + 6
        n1 := []uint64{0, 6}
        // Second number is 0<<64 + 3
        n2 := []uint64{0, 3}
        // Divide them together.
        quo, rem := bits.Div64(n1[0], n1[1], n2[1])
        nsum := []uint64{quo, rem}
        fmt.Printf("[%v %v] / %v = %v\n", n1[0], n1[1], n2[1], nsum)
        
        // First number is 2<<64 + 9223372036854775808
        n1 = []uint64{2, 0x8000000000000000}
        // Second number is 0<<64 + 9223372036854775808
        n2 = []uint64{0, 0x8000000000000000}
        // Divide them together.
        quo, rem = bits.Div64(n1[0], n1[1], n2[1])
        nsum = []uint64{quo, rem}
        fmt.Printf("[%v %v] / %v = %v\n", n1[0], n1[1], n2[1], nsum)
        

        Output:

        [0 6] / 3 = [2 0]
        [2 9223372036854775808] / 9223372036854775808 = [5 0]
        

        func LeadingZeros

        func LeadingZeros(x uint) int

        LeadingZeros returns the number of leading zero bits in x; the result is UintSize for x == 0.

        func LeadingZeros16

        func LeadingZeros16(x uint16) int

        LeadingZeros16 returns the number of leading zero bits in x; the result is 16 for x == 0.

        Example

        Code:

        fmt.Printf("LeadingZeros16(%016b) = %d\n", 1, bits.LeadingZeros16(1))
        

        Output:

        LeadingZeros16(0000000000000001) = 15
        

        func LeadingZeros32

        func LeadingZeros32(x uint32) int

        LeadingZeros32 returns the number of leading zero bits in x; the result is 32 for x == 0.

        Example

        Code:

        fmt.Printf("LeadingZeros32(%032b) = %d\n", 1, bits.LeadingZeros32(1))
        

        Output:

        LeadingZeros32(00000000000000000000000000000001) = 31
        

        func LeadingZeros64

        func LeadingZeros64(x uint64) int

        LeadingZeros64 returns the number of leading zero bits in x; the result is 64 for x == 0.

        Example

        Code:

        fmt.Printf("LeadingZeros64(%064b) = %d\n", 1, bits.LeadingZeros64(1))
        

        Output:

        LeadingZeros64(0000000000000000000000000000000000000000000000000000000000000001) = 63
        

        func LeadingZeros8

        func LeadingZeros8(x uint8) int

        LeadingZeros8 returns the number of leading zero bits in x; the result is 8 for x == 0.

        Example

        Code:

        fmt.Printf("LeadingZeros8(%08b) = %d\n", 1, bits.LeadingZeros8(1))
        

        Output:

        LeadingZeros8(00000001) = 7
        

        func Len

        func Len(x uint) int

        Len returns the minimum number of bits required to represent x; the result is 0 for x == 0.

        func Len16

        func Len16(x uint16) (n int)

        Len16 returns the minimum number of bits required to represent x; the result is 0 for x == 0.

        Example

        Code:

        fmt.Printf("Len16(%016b) = %d\n", 8, bits.Len16(8))
        

        Output:

        Len16(0000000000001000) = 4
        

        func Len32

        func Len32(x uint32) (n int)

        Len32 returns the minimum number of bits required to represent x; the result is 0 for x == 0.

        Example

        Code:

        fmt.Printf("Len32(%032b) = %d\n", 8, bits.Len32(8))
        

        Output:

        Len32(00000000000000000000000000001000) = 4
        

        func Len64

        func Len64(x uint64) (n int)

        Len64 returns the minimum number of bits required to represent x; the result is 0 for x == 0.

        Example

        Code:

        fmt.Printf("Len64(%064b) = %d\n", 8, bits.Len64(8))
        

        Output:

        Len64(0000000000000000000000000000000000000000000000000000000000001000) = 4
        

        func Len8

        func Len8(x uint8) int

        Len8 returns the minimum number of bits required to represent x; the result is 0 for x == 0.

        Example

        Code:

        fmt.Printf("Len8(%08b) = %d\n", 8, bits.Len8(8))
        

        Output:

        Len8(00001000) = 4
        

        func Mul

        func Mul(x, y uint) (hi, lo uint)

        Mul returns the full-width product of x and y: (hi, lo) = x * y with the product bits' upper half returned in hi and the lower half returned in lo.

        This function's execution time does not depend on the inputs.

        func Mul32

        func Mul32(x, y uint32) (hi, lo uint32)

        Mul32 returns the 64-bit product of x and y: (hi, lo) = x * y with the product bits' upper half returned in hi and the lower half returned in lo.

        This function's execution time does not depend on the inputs.

        Example

        Code:

        // First number is 0<<32 + 12
        n1 := []uint32{0, 12}
        // Second number is 0<<32 + 12
        n2 := []uint32{0, 12}
        // Multiply them together without producing overflow.
        hi, lo := bits.Mul32(n1[1], n2[1])
        nsum := []uint32{hi, lo}
        fmt.Printf("%v * %v = %v\n", n1[1], n2[1], nsum)
        
        // First number is 0<<32 + 2147483648
        n1 = []uint32{0, 0x80000000}
        // Second number is 0<<32 + 2
        n2 = []uint32{0, 2}
        // Multiply them together producing overflow.
        hi, lo = bits.Mul32(n1[1], n2[1])
        nsum = []uint32{hi, lo}
        fmt.Printf("%v * %v = %v\n", n1[1], n2[1], nsum)
        

        Output:

        12 * 12 = [0 144]
        2147483648 * 2 = [1 0]
        

        func Mul64

        func Mul64(x, y uint64) (hi, lo uint64)

        Mul64 returns the 128-bit product of x and y: (hi, lo) = x * y with the product bits' upper half returned in hi and the lower half returned in lo.

        This function's execution time does not depend on the inputs.

        Example

        Code:

        // First number is 0<<64 + 12
        n1 := []uint64{0, 12}
        // Second number is 0<<64 + 12
        n2 := []uint64{0, 12}
        // Multiply them together without producing overflow.
        hi, lo := bits.Mul64(n1[1], n2[1])
        nsum := []uint64{hi, lo}
        fmt.Printf("%v * %v = %v\n", n1[1], n2[1], nsum)
        
        // First number is 0<<64 + 9223372036854775808
        n1 = []uint64{0, 0x8000000000000000}
        // Second number is 0<<64 + 2
        n2 = []uint64{0, 2}
        // Multiply them together producing overflow.
        hi, lo = bits.Mul64(n1[1], n2[1])
        nsum = []uint64{hi, lo}
        fmt.Printf("%v * %v = %v\n", n1[1], n2[1], nsum)
        

        Output:

        12 * 12 = [0 144]
        9223372036854775808 * 2 = [1 0]
        

        func OnesCount

        func OnesCount(x uint) int

        OnesCount returns the number of one bits ("population count") in x.

        Example

        Code:

        fmt.Printf("OnesCount(%b) = %d\n", 14, bits.OnesCount(14))
        

        Output:

        OnesCount(1110) = 3
        

        func OnesCount16

        func OnesCount16(x uint16) int

        OnesCount16 returns the number of one bits ("population count") in x.

        Example

        Code:

        fmt.Printf("OnesCount16(%016b) = %d\n", 14, bits.OnesCount16(14))
        

        Output:

        OnesCount16(0000000000001110) = 3
        

        func OnesCount32

        func OnesCount32(x uint32) int

        OnesCount32 returns the number of one bits ("population count") in x.

        Example

        Code:

        fmt.Printf("OnesCount32(%032b) = %d\n", 14, bits.OnesCount32(14))
        

        Output:

        OnesCount32(00000000000000000000000000001110) = 3
        

        func OnesCount64

        func OnesCount64(x uint64) int

        OnesCount64 returns the number of one bits ("population count") in x.

        Example

        Code:

        fmt.Printf("OnesCount64(%064b) = %d\n", 14, bits.OnesCount64(14))
        

        Output:

        OnesCount64(0000000000000000000000000000000000000000000000000000000000001110) = 3
        

        func OnesCount8

        func OnesCount8(x uint8) int

        OnesCount8 returns the number of one bits ("population count") in x.

        Example

        Code:

        fmt.Printf("OnesCount8(%08b) = %d\n", 14, bits.OnesCount8(14))
        

        Output:

        OnesCount8(00001110) = 3
        

        func Rem

        func Rem(hi, lo, y uint) uint

        Rem returns the remainder of (hi, lo) divided by y. Rem panics for y == 0 (division by zero) but, unlike Div, it doesn't panic on a quotient overflow.

        func Rem32

        func Rem32(hi, lo, y uint32) uint32

        Rem32 returns the remainder of (hi, lo) divided by y. Rem32 panics for y == 0 (division by zero) but, unlike Div32, it doesn't panic on a quotient overflow.

        func Rem64

        func Rem64(hi, lo, y uint64) uint64

        Rem64 returns the remainder of (hi, lo) divided by y. Rem64 panics for y == 0 (division by zero) but, unlike Div64, it doesn't panic on a quotient overflow.

        func Reverse

        func Reverse(x uint) uint

        Reverse returns the value of x with its bits in reversed order.

        func Reverse16

        func Reverse16(x uint16) uint16

        Reverse16 returns the value of x with its bits in reversed order.

        Example

        Code:

        fmt.Printf("%016b\n", 19)
        fmt.Printf("%016b\n", bits.Reverse16(19))
        

        Output:

        0000000000010011
        1100100000000000
        

        func Reverse32

        func Reverse32(x uint32) uint32

        Reverse32 returns the value of x with its bits in reversed order.

        Example

        Code:

        fmt.Printf("%032b\n", 19)
        fmt.Printf("%032b\n", bits.Reverse32(19))
        

        Output:

        00000000000000000000000000010011
        11001000000000000000000000000000
        

        func Reverse64

        func Reverse64(x uint64) uint64

        Reverse64 returns the value of x with its bits in reversed order.

        Example

        Code:

        fmt.Printf("%064b\n", 19)
        fmt.Printf("%064b\n", bits.Reverse64(19))
        

        Output:

        0000000000000000000000000000000000000000000000000000000000010011
        1100100000000000000000000000000000000000000000000000000000000000
        

        func Reverse8

        func Reverse8(x uint8) uint8

        Reverse8 returns the value of x with its bits in reversed order.

        Example

        Code:

        fmt.Printf("%08b\n", 19)
        fmt.Printf("%08b\n", bits.Reverse8(19))
        

        Output:

        00010011
        11001000
        

        func ReverseBytes

        func ReverseBytes(x uint) uint

        ReverseBytes returns the value of x with its bytes in reversed order.

        This function's execution time does not depend on the inputs.

        func ReverseBytes16

        func ReverseBytes16(x uint16) uint16

        ReverseBytes16 returns the value of x with its bytes in reversed order.

        This function's execution time does not depend on the inputs.

        Example

        Code:

        fmt.Printf("%016b\n", 15)
        fmt.Printf("%016b\n", bits.ReverseBytes16(15))
        

        Output:

        0000000000001111
        0000111100000000
        

        func ReverseBytes32

        func ReverseBytes32(x uint32) uint32

        ReverseBytes32 returns the value of x with its bytes in reversed order.

        This function's execution time does not depend on the inputs.

        Example

        Code:

        fmt.Printf("%032b\n", 15)
        fmt.Printf("%032b\n", bits.ReverseBytes32(15))
        

        Output:

        00000000000000000000000000001111
        00001111000000000000000000000000
        

        func ReverseBytes64

        func ReverseBytes64(x uint64) uint64

        ReverseBytes64 returns the value of x with its bytes in reversed order.

        This function's execution time does not depend on the inputs.

        Example

        Code:

        fmt.Printf("%064b\n", 15)
        fmt.Printf("%064b\n", bits.ReverseBytes64(15))
        

        Output:

        0000000000000000000000000000000000000000000000000000000000001111
        0000111100000000000000000000000000000000000000000000000000000000
        

        func RotateLeft

        func RotateLeft(x uint, k int) uint

        RotateLeft returns the value of x rotated left by (k mod UintSize) bits. To rotate x right by k bits, call RotateLeft(x, -k).

        This function's execution time does not depend on the inputs.

        func RotateLeft16

        func RotateLeft16(x uint16, k int) uint16

        RotateLeft16 returns the value of x rotated left by (k mod 16) bits. To rotate x right by k bits, call RotateLeft16(x, -k).

        This function's execution time does not depend on the inputs.

        Example

        Code:

        fmt.Printf("%016b\n", 15)
        fmt.Printf("%016b\n", bits.RotateLeft16(15, 2))
        fmt.Printf("%016b\n", bits.RotateLeft16(15, -2))
        

        Output:

        0000000000001111
        0000000000111100
        1100000000000011
        

        func RotateLeft32

        func RotateLeft32(x uint32, k int) uint32

        RotateLeft32 returns the value of x rotated left by (k mod 32) bits. To rotate x right by k bits, call RotateLeft32(x, -k).

        This function's execution time does not depend on the inputs.

        Example

        Code:

        fmt.Printf("%032b\n", 15)
        fmt.Printf("%032b\n", bits.RotateLeft32(15, 2))
        fmt.Printf("%032b\n", bits.RotateLeft32(15, -2))
        

        Output:

        00000000000000000000000000001111
        00000000000000000000000000111100
        11000000000000000000000000000011
        

        func RotateLeft64

        func RotateLeft64(x uint64, k int) uint64

        RotateLeft64 returns the value of x rotated left by (k mod 64) bits. To rotate x right by k bits, call RotateLeft64(x, -k).

        This function's execution time does not depend on the inputs.

        Example

        Code:

        fmt.Printf("%064b\n", 15)
        fmt.Printf("%064b\n", bits.RotateLeft64(15, 2))
        fmt.Printf("%064b\n", bits.RotateLeft64(15, -2))
        

        Output:

        0000000000000000000000000000000000000000000000000000000000001111
        0000000000000000000000000000000000000000000000000000000000111100
        1100000000000000000000000000000000000000000000000000000000000011
        

        func RotateLeft8

        func RotateLeft8(x uint8, k int) uint8

        RotateLeft8 returns the value of x rotated left by (k mod 8) bits. To rotate x right by k bits, call RotateLeft8(x, -k).

        This function's execution time does not depend on the inputs.

        Example

        Code:

        fmt.Printf("%08b\n", 15)
        fmt.Printf("%08b\n", bits.RotateLeft8(15, 2))
        fmt.Printf("%08b\n", bits.RotateLeft8(15, -2))
        

        Output:

        00001111
        00111100
        11000011
        

        func Sub

        func Sub(x, y, borrow uint) (diff, borrowOut uint)

        Sub returns the difference of x, y and borrow: diff = x - y - borrow. The borrow input must be 0 or 1; otherwise the behavior is undefined. The borrowOut output is guaranteed to be 0 or 1.

        This function's execution time does not depend on the inputs.

        func Sub32

        func Sub32(x, y, borrow uint32) (diff, borrowOut uint32)

        Sub32 returns the difference of x, y and borrow, diff = x - y - borrow. The borrow input must be 0 or 1; otherwise the behavior is undefined. The borrowOut output is guaranteed to be 0 or 1.

        This function's execution time does not depend on the inputs.

        Example

        Code:

        // First number is 33<<32 + 23
        n1 := []uint32{33, 23}
        // Second number is 21<<32 + 12
        n2 := []uint32{21, 12}
        // Sub them together without producing carry.
        d1, carry := bits.Sub32(n1[1], n2[1], 0)
        d0, _ := bits.Sub32(n1[0], n2[0], carry)
        nsum := []uint32{d0, d1}
        fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
        
        // First number is 3<<32 + 2147483647
        n1 = []uint32{3, 0x7fffffff}
        // Second number is 1<<32 + 2147483648
        n2 = []uint32{1, 0x80000000}
        // Sub them together producing carry.
        d1, carry = bits.Sub32(n1[1], n2[1], 0)
        d0, _ = bits.Sub32(n1[0], n2[0], carry)
        nsum = []uint32{d0, d1}
        fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
        

        Output:

        [33 23] - [21 12] = [12 11] (carry bit was 0)
        [3 2147483647] - [1 2147483648] = [1 4294967295] (carry bit was 1)
        

        func Sub64

        func Sub64(x, y, borrow uint64) (diff, borrowOut uint64)

        Sub64 returns the difference of x, y and borrow: diff = x - y - borrow. The borrow input must be 0 or 1; otherwise the behavior is undefined. The borrowOut output is guaranteed to be 0 or 1.

        This function's execution time does not depend on the inputs.

        Example

        Code:

        // First number is 33<<64 + 23
        n1 := []uint64{33, 23}
        // Second number is 21<<64 + 12
        n2 := []uint64{21, 12}
        // Sub them together without producing carry.
        d1, carry := bits.Sub64(n1[1], n2[1], 0)
        d0, _ := bits.Sub64(n1[0], n2[0], carry)
        nsum := []uint64{d0, d1}
        fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
        
        // First number is 3<<64 + 9223372036854775807
        n1 = []uint64{3, 0x7fffffffffffffff}
        // Second number is 1<<64 + 9223372036854775808
        n2 = []uint64{1, 0x8000000000000000}
        // Sub them together producing carry.
        d1, carry = bits.Sub64(n1[1], n2[1], 0)
        d0, _ = bits.Sub64(n1[0], n2[0], carry)
        nsum = []uint64{d0, d1}
        fmt.Printf("%v - %v = %v (carry bit was %v)\n", n1, n2, nsum, carry)
        

        Output:

        [33 23] - [21 12] = [12 11] (carry bit was 0)
        [3 9223372036854775807] - [1 9223372036854775808] = [1 18446744073709551615] (carry bit was 1)
        

        func TrailingZeros

        func TrailingZeros(x uint) int

        TrailingZeros returns the number of trailing zero bits in x; the result is UintSize for x == 0.

        func TrailingZeros16

        func TrailingZeros16(x uint16) int

        TrailingZeros16 returns the number of trailing zero bits in x; the result is 16 for x == 0.

        Example

        Code:

        fmt.Printf("TrailingZeros16(%016b) = %d\n", 14, bits.TrailingZeros16(14))
        

        Output:

        TrailingZeros16(0000000000001110) = 1
        

        func TrailingZeros32

        func TrailingZeros32(x uint32) int

        TrailingZeros32 returns the number of trailing zero bits in x; the result is 32 for x == 0.

        Example

        Code:

        fmt.Printf("TrailingZeros32(%032b) = %d\n", 14, bits.TrailingZeros32(14))
        

        Output:

        TrailingZeros32(00000000000000000000000000001110) = 1
        

        func TrailingZeros64

        func TrailingZeros64(x uint64) int

        TrailingZeros64 returns the number of trailing zero bits in x; the result is 64 for x == 0.

        Example

        Code:

        fmt.Printf("TrailingZeros64(%064b) = %d\n", 14, bits.TrailingZeros64(14))
        

        Output:

        TrailingZeros64(0000000000000000000000000000000000000000000000000000000000001110) = 1
        

        func TrailingZeros8

        func TrailingZeros8(x uint8) int

        TrailingZeros8 returns the number of trailing zero bits in x; the result is 8 for x == 0.

        Example

        Code:

        fmt.Printf("TrailingZeros8(%08b) = %d\n", 14, bits.TrailingZeros8(14))
        

        Output:

        TrailingZeros8(00001110) = 1
        
        cmplx - Go Documentation Server
        ...

        Package cmplx

        import "math/cmplx"
        Overview
        Index
        Examples

        Overview ▾

        Package cmplx provides basic constants and mathematical functions for complex numbers. Special case handling conforms to the C99 standard Annex G IEC 60559-compatible complex arithmetic.

        func Abs

        func Abs(x complex128) float64

        Abs returns the absolute value (also called the modulus) of x.

        Example

        Code:

        fmt.Printf("%.1f", cmplx.Abs(3+4i))
        

        Output:

        5.0
        

        func Acos

        func Acos(x complex128) complex128

        Acos returns the inverse cosine of x.

        func Acosh

        func Acosh(x complex128) complex128

        Acosh returns the inverse hyperbolic cosine of x.

        func Asin

        func Asin(x complex128) complex128

        Asin returns the inverse sine of x.

        func Asinh

        func Asinh(x complex128) complex128

        Asinh returns the inverse hyperbolic sine of x.

        func Atan

        func Atan(x complex128) complex128

        Atan returns the inverse tangent of x.

        func Atanh

        func Atanh(x complex128) complex128

        Atanh returns the inverse hyperbolic tangent of x.

        func Conj

        func Conj(x complex128) complex128

        Conj returns the complex conjugate of x.

        func Cos

        func Cos(x complex128) complex128

        Cos returns the cosine of x.

        func Cosh

        func Cosh(x complex128) complex128

        Cosh returns the hyperbolic cosine of x.

        func Cot

        func Cot(x complex128) complex128

        Cot returns the cotangent of x.

        func Exp

        func Exp(x complex128) complex128

        Exp returns e**x, the base-e exponential of x.

        Example

        ExampleExp computes Euler's identity.

        Code:

        fmt.Printf("%.1f", cmplx.Exp(1i*math.Pi)+1)
        

        Output:

        (0.0+0.0i)
        

        func Inf

        func Inf() complex128

        Inf returns a complex infinity, complex(+Inf, +Inf).

        func IsInf

        func IsInf(x complex128) bool

        IsInf reports whether either real(x) or imag(x) is an infinity.

        func IsNaN

        func IsNaN(x complex128) bool

        IsNaN reports whether either real(x) or imag(x) is NaN and neither is an infinity.

        func Log

        func Log(x complex128) complex128

        Log returns the natural logarithm of x.

        func Log10

        func Log10(x complex128) complex128

        Log10 returns the decimal logarithm of x.

        func NaN

        func NaN() complex128

        NaN returns a complex “not-a-number” value.

        func Phase

        func Phase(x complex128) float64

        Phase returns the phase (also called the argument) of x. The returned value is in the range [-Pi, Pi].

        func Polar

        func Polar(x complex128) (r, θ float64)

        Polar returns the absolute value r and phase θ of x, such that x = r * e**θi. The phase is in the range [-Pi, Pi].

        Example

        Code:

        r, theta := cmplx.Polar(2i)
        fmt.Printf("r: %.1f, θ: %.1f*π", r, theta/math.Pi)
        

        Output:

        r: 2.0, θ: 0.5*π
        

        func Pow

        func Pow(x, y complex128) complex128

        Pow returns x**y, the base-x exponential of y. For generalized compatibility with math.Pow:

        Pow(0, ±0) returns 1+0i
        Pow(0, c) for real(c)<0 returns Inf+0i if imag(c) is zero, otherwise Inf+Inf i.
        

        func Rect

        func Rect(r, θ float64) complex128

        Rect returns the complex number x with polar coordinates r, θ.

        func Sin

        func Sin(x complex128) complex128

        Sin returns the sine of x.

        func Sinh

        func Sinh(x complex128) complex128

        Sinh returns the hyperbolic sine of x.

        func Sqrt

        func Sqrt(x complex128) complex128

        Sqrt returns the square root of x. The result r is chosen so that real(r) ≥ 0 and imag(r) has the same sign as imag(x).

        func Tan

        func Tan(x complex128) complex128

        Tan returns the tangent of x.

        func Tanh

        func Tanh(x complex128) complex128

        Tanh returns the hyperbolic tangent of x.

        rand - Go Documentation Server
        ...

        Package rand

        import "math/rand"
        Overview
        Index
        Examples
        Subdirectories

        Overview ▾

        Package rand implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.

        Random numbers are generated by a Source, usually wrapped in a Rand. Both types should be used by a single goroutine at a time: sharing among multiple goroutines requires some kind of synchronization.

        Top-level functions, such as Float64 and Int, are safe for concurrent use by multiple goroutines.

        This package's outputs might be easily predictable regardless of how it's seeded. For random numbers suitable for security-sensitive work, see the crypto/rand package.

        Example

        Code:

        answers := []string{
            "It is certain",
            "It is decidedly so",
            "Without a doubt",
            "Yes definitely",
            "You may rely on it",
            "As I see it yes",
            "Most likely",
            "Outlook good",
            "Yes",
            "Signs point to yes",
            "Reply hazy try again",
            "Ask again later",
            "Better not tell you now",
            "Cannot predict now",
            "Concentrate and ask again",
            "Don't count on it",
            "My reply is no",
            "My sources say no",
            "Outlook not so good",
            "Very doubtful",
        }
        fmt.Println("Magic 8-Ball says:", answers[rand.Intn(len(answers))])
        

        Example (Rand)

        This example shows the use of each of the methods on a *Rand. The use of the global functions is the same, without the receiver.

        Code:

        // Create and seed the generator.
        // Typically a non-fixed seed should be used, such as time.Now().UnixNano().
        // Using a fixed seed will produce the same output on every run.
        r := rand.New(rand.NewSource(99))
        
        // The tabwriter here helps us generate aligned output.
        w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
        defer w.Flush()
        show := func(name string, v1, v2, v3 any) {
            fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3)
        }
        
        // Float32 and Float64 values are in [0, 1).
        show("Float32", r.Float32(), r.Float32(), r.Float32())
        show("Float64", r.Float64(), r.Float64(), r.Float64())
        
        // ExpFloat64 values have an average of 1 but decay exponentially.
        show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())
        
        // NormFloat64 values have an average of 0 and a standard deviation of 1.
        show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())
        
        // Int31, Int63, and Uint32 generate values of the given width.
        // The Int method (not shown) is like either Int31 or Int63
        // depending on the size of 'int'.
        show("Int31", r.Int31(), r.Int31(), r.Int31())
        show("Int63", r.Int63(), r.Int63(), r.Int63())
        show("Uint32", r.Uint32(), r.Uint32(), r.Uint32())
        
        // Intn, Int31n, and Int63n limit their output to be < n.
        // They do so more carefully than using r.Int()%n.
        show("Intn(10)", r.Intn(10), r.Intn(10), r.Intn(10))
        show("Int31n(10)", r.Int31n(10), r.Int31n(10), r.Int31n(10))
        show("Int63n(10)", r.Int63n(10), r.Int63n(10), r.Int63n(10))
        
        // Perm generates a random permutation of the numbers [0, n).
        show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
        

        Output:

        Float32     0.2635776           0.6358173           0.6718283
        Float64     0.628605430454327   0.4504798828572669  0.9562755949377957
        ExpFloat64  0.3362240648200941  1.4256072328483647  0.24354758816173044
        NormFloat64 0.17233959114940064 1.577014951434847   0.04259129641113857
        Int31       1501292890          1486668269          182840835
        Int63       3546343826724305832 5724354148158589552 5239846799706671610
        Uint32      2760229429          296659907           1922395059
        Intn(10)    1                   2                   5
        Int31n(10)  4                   7                   8
        Int63n(10)  7                   6                   3
        Perm        [1 4 2 3 0]         [4 2 1 3 0]         [1 2 4 0 3]
        

        func ExpFloat64

        func ExpFloat64() float64

        ExpFloat64 returns an exponentially distributed float64 in the range (0, +[math.MaxFloat64]] with an exponential distribution whose rate parameter (lambda) is 1 and whose mean is 1/lambda (1) from the default Source. To produce a distribution with a different rate parameter, callers can adjust the output using:

        sample = ExpFloat64() / desiredRateParameter
        

        func Float32

        func Float32() float32

        Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0) from the default Source.

        func Float64

        func Float64() float64

        Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0) from the default Source.

        func Int

        func Int() int

        Int returns a non-negative pseudo-random int from the default Source.

        func Int31

        func Int31() int32

        Int31 returns a non-negative pseudo-random 31-bit integer as an int32 from the default Source.

        func Int31n

        func Int31n(n int32) int32

        Int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

        func Int63

        func Int63() int64

        Int63 returns a non-negative pseudo-random 63-bit integer as an int64 from the default Source.

        func Int63n

        func Int63n(n int64) int64

        Int63n returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

        func Intn

        func Intn(n int) int

        Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

        Example

        Code:

        fmt.Println(rand.Intn(100))
        fmt.Println(rand.Intn(100))
        fmt.Println(rand.Intn(100))
        

        func NormFloat64

        func NormFloat64() float64

        NormFloat64 returns a normally distributed float64 in the range [-math.MaxFloat64, +[math.MaxFloat64]] with standard normal distribution (mean = 0, stddev = 1) from the default Source. To produce a different normal distribution, callers can adjust the output using:

        sample = NormFloat64() * desiredStdDev + desiredMean
        

        func Perm

        func Perm(n int) []int

        Perm returns, as a slice of n ints, a pseudo-random permutation of the integers in the half-open interval [0,n) from the default Source.

        Example

        Code:

        for _, value := range rand.Perm(3) {
            fmt.Println(value)
        }
        
        

        Output:

        1
        2
        0
        

        func Read

        func Read(p []byte) (n int, err error)

        Read generates len(p) random bytes from the default Source and writes them into p. It always returns len(p) and a nil error. Read, unlike the Rand.Read method, is safe for concurrent use.

        Deprecated: For almost all use cases, crypto/rand.Read is more appropriate.

        func Seed

        func Seed(seed int64)

        Seed uses the provided seed value to initialize the default Source to a deterministic state. Seed values that have the same remainder when divided by 2³¹-1 generate the same pseudo-random sequence. Seed, unlike the Rand.Seed method, is safe for concurrent use.

        If Seed is not called, the generator is seeded randomly at program startup.

        Prior to Go 1.20, the generator was seeded like Seed(1) at program startup. To force the old behavior, call Seed(1) at program startup. Alternately, set GODEBUG=randautoseed=0 in the environment before making any calls to functions in this package.

        Deprecated: As of Go 1.20 there is no reason to call Seed with a random value. Programs that call Seed with a known value to get a specific sequence of results should use New(NewSource(seed)) to obtain a local random generator.

        func Shuffle

        func Shuffle(n int, swap func(i, j int))

        Shuffle pseudo-randomizes the order of elements using the default Source. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.

        Example

        Code:

        words := strings.Fields("ink runs from the corners of my mouth")
        rand.Shuffle(len(words), func(i, j int) {
            words[i], words[j] = words[j], words[i]
        })
        fmt.Println(words)
        

        Example (SlicesInUnison)

        Code:

        numbers := []byte("12345")
        letters := []byte("ABCDE")
        // Shuffle numbers, swapping corresponding entries in letters at the same time.
        rand.Shuffle(len(numbers), func(i, j int) {
            numbers[i], numbers[j] = numbers[j], numbers[i]
            letters[i], letters[j] = letters[j], letters[i]
        })
        for i := range numbers {
            fmt.Printf("%c: %c\n", letters[i], numbers[i])
        }
        

        func Uint32

        func Uint32() uint32

        Uint32 returns a pseudo-random 32-bit value as a uint32 from the default Source.

        func Uint64

        func Uint64() uint64

        Uint64 returns a pseudo-random 64-bit value as a uint64 from the default Source.

        type Rand

        A Rand is a source of random numbers.

        type Rand struct {
            // contains filtered or unexported fields
        }
        

        func New

        func New(src Source) *Rand

        New returns a new Rand that uses random values from src to generate other random values.

        func (*Rand) ExpFloat64

        func (r *Rand) ExpFloat64() float64

        ExpFloat64 returns an exponentially distributed float64 in the range (0, +[math.MaxFloat64]] with an exponential distribution whose rate parameter (lambda) is 1 and whose mean is 1/lambda (1). To produce a distribution with a different rate parameter, callers can adjust the output using:

        sample = ExpFloat64() / desiredRateParameter
        

        func (*Rand) Float32

        func (r *Rand) Float32() float32

        Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0).

        func (*Rand) Float64

        func (r *Rand) Float64() float64

        Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0).

        func (*Rand) Int

        func (r *Rand) Int() int

        Int returns a non-negative pseudo-random int.

        func (*Rand) Int31

        func (r *Rand) Int31() int32

        Int31 returns a non-negative pseudo-random 31-bit integer as an int32.

        func (*Rand) Int31n

        func (r *Rand) Int31n(n int32) int32

        Int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

        func (*Rand) Int63

        func (r *Rand) Int63() int64

        Int63 returns a non-negative pseudo-random 63-bit integer as an int64.

        func (*Rand) Int63n

        func (r *Rand) Int63n(n int64) int64

        Int63n returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

        func (*Rand) Intn

        func (r *Rand) Intn(n int) int

        Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

        func (*Rand) NormFloat64

        func (r *Rand) NormFloat64() float64

        NormFloat64 returns a normally distributed float64 in the range -math.MaxFloat64 through +[math.MaxFloat64] inclusive, with standard normal distribution (mean = 0, stddev = 1). To produce a different normal distribution, callers can adjust the output using:

        sample = NormFloat64() * desiredStdDev + desiredMean
        

        func (*Rand) Perm

        func (r *Rand) Perm(n int) []int

        Perm returns, as a slice of n ints, a pseudo-random permutation of the integers in the half-open interval [0,n).

        func (*Rand) Read

        func (r *Rand) Read(p []byte) (n int, err error)

        Read generates len(p) random bytes and writes them into p. It always returns len(p) and a nil error. Read should not be called concurrently with any other Rand method.

        func (*Rand) Seed

        func (r *Rand) Seed(seed int64)

        Seed uses the provided seed value to initialize the generator to a deterministic state. Seed should not be called concurrently with any other Rand method.

        func (*Rand) Shuffle

        func (r *Rand) Shuffle(n int, swap func(i, j int))

        Shuffle pseudo-randomizes the order of elements. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.

        func (*Rand) Uint32

        func (r *Rand) Uint32() uint32

        Uint32 returns a pseudo-random 32-bit value as a uint32.

        func (*Rand) Uint64

        func (r *Rand) Uint64() uint64

        Uint64 returns a pseudo-random 64-bit value as a uint64.

        type Source

        A Source represents a source of uniformly-distributed pseudo-random int64 values in the range [0, 1<<63).

        A Source is not safe for concurrent use by multiple goroutines.

        type Source interface {
            Int63() int64
            Seed(seed int64)
        }

        func NewSource

        func NewSource(seed int64) Source

        NewSource returns a new pseudo-random Source seeded with the given value. Unlike the default Source used by top-level functions, this source is not safe for concurrent use by multiple goroutines. The returned Source implements Source64.

        type Source64

        A Source64 is a Source that can also generate uniformly-distributed pseudo-random uint64 values in the range [0, 1<<64) directly. If a Rand r's underlying Source s implements Source64, then r.Uint64 returns the result of one call to s.Uint64 instead of making two calls to s.Int63.

        type Source64 interface {
            Source
            Uint64() uint64
        }

        type Zipf

        A Zipf generates Zipf distributed variates.

        type Zipf struct {
            // contains filtered or unexported fields
        }
        

        func NewZipf

        func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf

        NewZipf returns a Zipf variate generator. The generator generates values k ∈ [0, imax] such that P(k) is proportional to (v + k) ** (-s). Requirements: s > 1 and v >= 1.

        func (*Zipf) Uint64

        func (z *Zipf) Uint64() uint64

        Uint64 returns a value drawn from the Zipf distribution described by the Zipf object.

        Subdirectories

        Name Synopsis
        ..
        v2 Package rand implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.
        rand - Go Documentation Server
        ...

        Package rand

        import "math/rand/v2"
        Overview
        Index
        Examples

        Overview ▾

        Package rand implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.

        Random numbers are generated by a Source, usually wrapped in a Rand. Both types should be used by a single goroutine at a time: sharing among multiple goroutines requires some kind of synchronization.

        Top-level functions, such as Float64 and Int, are safe for concurrent use by multiple goroutines.

        This package's outputs might be easily predictable regardless of how it's seeded. For random numbers suitable for security-sensitive work, see the crypto/rand package.

        Example

        Code:

        answers := []string{
            "It is certain",
            "It is decidedly so",
            "Without a doubt",
            "Yes definitely",
            "You may rely on it",
            "As I see it yes",
            "Most likely",
            "Outlook good",
            "Yes",
            "Signs point to yes",
            "Reply hazy try again",
            "Ask again later",
            "Better not tell you now",
            "Cannot predict now",
            "Concentrate and ask again",
            "Don't count on it",
            "My reply is no",
            "My sources say no",
            "Outlook not so good",
            "Very doubtful",
        }
        fmt.Println("Magic 8-Ball says:", answers[rand.IntN(len(answers))])
        

        Example (Rand)

        This example shows the use of each of the methods on a *Rand. The use of the global functions is the same, without the receiver.

        Code:

        // Create and seed the generator.
        // Typically a non-fixed seed should be used, such as Uint64(), Uint64().
        // Using a fixed seed will produce the same output on every run.
        r := rand.New(rand.NewPCG(1, 2))
        
        // The tabwriter here helps us generate aligned output.
        w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
        defer w.Flush()
        show := func(name string, v1, v2, v3 any) {
            fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3)
        }
        
        // Float32 and Float64 values are in [0, 1).
        show("Float32", r.Float32(), r.Float32(), r.Float32())
        show("Float64", r.Float64(), r.Float64(), r.Float64())
        
        // ExpFloat64 values have an average of 1 but decay exponentially.
        show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())
        
        // NormFloat64 values have an average of 0 and a standard deviation of 1.
        show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())
        
        // Int32, Int64, and Uint32 generate values of the given width.
        // The Int method (not shown) is like either Int32 or Int64
        // depending on the size of 'int'.
        show("Int32", r.Int32(), r.Int32(), r.Int32())
        show("Int64", r.Int64(), r.Int64(), r.Int64())
        show("Uint32", r.Uint32(), r.Uint32(), r.Uint32())
        
        // IntN, Int32N, and Int64N limit their output to be < n.
        // They do so more carefully than using r.Int()%n.
        show("IntN(10)", r.IntN(10), r.IntN(10), r.IntN(10))
        show("Int32N(10)", r.Int32N(10), r.Int32N(10), r.Int32N(10))
        show("Int64N(10)", r.Int64N(10), r.Int64N(10), r.Int64N(10))
        
        // Perm generates a random permutation of the numbers [0, n).
        show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
        

        Output:

        Float32     0.95955694          0.8076733            0.8135684
        Float64     0.4297927436037299  0.797802349388613    0.3883664855410056
        ExpFloat64  0.43463410545541104 0.5513632046504593   0.7426404617374481
        NormFloat64 -0.9303318111676635 -0.04750789419852852 0.22248301107582735
        Int32       2020777787          260808523            851126509
        Int64       5231057920893523323 4257872588489500903  158397175702351138
        Uint32      314478343           1418758728           208955345
        IntN(10)    6                   2                    0
        Int32N(10)  3                   7                    7
        Int64N(10)  8                   9                    4
        Perm        [0 3 1 4 2]         [4 1 2 0 3]          [4 3 2 0 1]
        

        Index ▾

        func ExpFloat64() float64
        func Float32() float32
        func Float64() float64
        func Int() int
        func Int32() int32
        func Int32N(n int32) int32
        func Int64() int64
        func Int64N(n int64) int64
        func IntN(n int) int
        func N[Int intType](n Int) Int
        func NormFloat64() float64
        func Perm(n int) []int
        func Shuffle(n int, swap func(i, j int))
        func Uint32() uint32
        func Uint32N(n uint32) uint32
        func Uint64() uint64
        func Uint64N(n uint64) uint64
        func UintN(n uint) uint
        type ChaCha8
            func NewChaCha8(seed [32]byte) *ChaCha8
            func (c *ChaCha8) MarshalBinary() ([]byte, error)
            func (c *ChaCha8) Seed(seed [32]byte)
            func (c *ChaCha8) Uint64() uint64
            func (c *ChaCha8) UnmarshalBinary(data []byte) error
        type PCG
            func NewPCG(seed1, seed2 uint64) *PCG
            func (p *PCG) MarshalBinary() ([]byte, error)
            func (p *PCG) Seed(seed1, seed2 uint64)
            func (p *PCG) Uint64() uint64
            func (p *PCG) UnmarshalBinary(data []byte) error
        type Rand
            func New(src Source) *Rand
            func (r *Rand) ExpFloat64() float64
            func (r *Rand) Float32() float32
            func (r *Rand) Float64() float64
            func (r *Rand) Int() int
            func (r *Rand) Int32() int32
            func (r *Rand) Int32N(n int32) int32
            func (r *Rand) Int64() int64
            func (r *Rand) Int64N(n int64) int64
            func (r *Rand) IntN(n int) int
            func (r *Rand) NormFloat64() float64
            func (r *Rand) Perm(n int) []int
            func (r *Rand) Shuffle(n int, swap func(i, j int))
            func (r *Rand) Uint32() uint32
            func (r *Rand) Uint32N(n uint32) uint32
            func (r *Rand) Uint64() uint64
            func (r *Rand) Uint64N(n uint64) uint64
            func (r *Rand) UintN(n uint) uint
        type Source
        type Zipf
            func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf
            func (z *Zipf) Uint64() uint64

        Package files

        chacha8.go exp.go normal.go pcg.go rand.go zipf.go

        func ExpFloat64

        func ExpFloat64() float64

        ExpFloat64 returns an exponentially distributed float64 in the range (0, +math.MaxFloat64] with an exponential distribution whose rate parameter (lambda) is 1 and whose mean is 1/lambda (1) from the default Source. To produce a distribution with a different rate parameter, callers can adjust the output using:

        sample = ExpFloat64() / desiredRateParameter
        

        func Float32

        func Float32() float32

        Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0) from the default Source.

        func Float64

        func Float64() float64

        Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0) from the default Source.

        func Int

        func Int() int

        Int returns a non-negative pseudo-random int from the default Source.

        func Int32

        func Int32() int32

        Int32 returns a non-negative pseudo-random 31-bit integer as an int32 from the default Source.

        func Int32N

        func Int32N(n int32) int32

        Int32N returns, as an int32, a pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

        func Int64

        func Int64() int64

        Int64 returns a non-negative pseudo-random 63-bit integer as an int64 from the default Source.

        func Int64N

        func Int64N(n int64) int64

        Int64N returns, as an int64, a pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

        func IntN

        func IntN(n int) int

        IntN returns, as an int, a pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

        Example

        Code:

        fmt.Println(rand.IntN(100))
        fmt.Println(rand.IntN(100))
        fmt.Println(rand.IntN(100))
        

        func N

        func N[Int intType](n Int) Int

        N returns a pseudo-random number in the half-open interval [0,n) from the default Source. The type parameter Int can be any integer type. It panics if n <= 0.

        Example

        Code:

        // Print an int64 in the half-open interval [0, 100).
        fmt.Println(rand.N(int64(100)))
        
        // Sleep for a random duration between 0 and 100 milliseconds.
        time.Sleep(rand.N(100 * time.Millisecond))
        

        func NormFloat64

        func NormFloat64() float64

        NormFloat64 returns a normally distributed float64 in the range [-math.MaxFloat64, +math.MaxFloat64] with standard normal distribution (mean = 0, stddev = 1) from the default Source. To produce a different normal distribution, callers can adjust the output using:

        sample = NormFloat64() * desiredStdDev + desiredMean
        

        func Perm

        func Perm(n int) []int

        Perm returns, as a slice of n ints, a pseudo-random permutation of the integers in the half-open interval [0,n) from the default Source.

        Example

        Code:

        for _, value := range rand.Perm(3) {
            fmt.Println(value)
        }
        
        

        Output:

        1
        2
        0
        

        func Shuffle

        func Shuffle(n int, swap func(i, j int))

        Shuffle pseudo-randomizes the order of elements using the default Source. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.

        Example

        Code:

        words := strings.Fields("ink runs from the corners of my mouth")
        rand.Shuffle(len(words), func(i, j int) {
            words[i], words[j] = words[j], words[i]
        })
        fmt.Println(words)
        

        Example (SlicesInUnison)

        Code:

        numbers := []byte("12345")
        letters := []byte("ABCDE")
        // Shuffle numbers, swapping corresponding entries in letters at the same time.
        rand.Shuffle(len(numbers), func(i, j int) {
            numbers[i], numbers[j] = numbers[j], numbers[i]
            letters[i], letters[j] = letters[j], letters[i]
        })
        for i := range numbers {
            fmt.Printf("%c: %c\n", letters[i], numbers[i])
        }
        

        func Uint32

        func Uint32() uint32

        Uint32 returns a pseudo-random 32-bit value as a uint32 from the default Source.

        func Uint32N

        func Uint32N(n uint32) uint32

        Uint32N returns, as a uint32, a pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

        func Uint64

        func Uint64() uint64

        Uint64 returns a pseudo-random 64-bit value as a uint64 from the default Source.

        func Uint64N

        func Uint64N(n uint64) uint64

        Uint64N returns, as a uint64, a pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

        func UintN

        func UintN(n uint) uint

        UintN returns, as a uint, a pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

        type ChaCha8

        A ChaCha8 is a ChaCha8-based cryptographically strong random number generator.

        type ChaCha8 struct {
            // contains filtered or unexported fields
        }
        

        func NewChaCha8

        func NewChaCha8(seed [32]byte) *ChaCha8

        NewChaCha8 returns a new ChaCha8 seeded with the given seed.

        func (*ChaCha8) MarshalBinary

        func (c *ChaCha8) MarshalBinary() ([]byte, error)

        MarshalBinary implements the encoding.BinaryMarshaler interface.

        func (*ChaCha8) Seed

        func (c *ChaCha8) Seed(seed [32]byte)

        Seed resets the ChaCha8 to behave the same way as NewChaCha8(seed).

        func (*ChaCha8) Uint64

        func (c *ChaCha8) Uint64() uint64

        Uint64 returns a uniformly distributed random uint64 value.

        func (*ChaCha8) UnmarshalBinary

        func (c *ChaCha8) UnmarshalBinary(data []byte) error

        UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

        type PCG

        A PCG is a PCG generator with 128 bits of internal state. A zero PCG is equivalent to NewPCG(0, 0).

        type PCG struct {
            // contains filtered or unexported fields
        }
        

        func NewPCG

        func NewPCG(seed1, seed2 uint64) *PCG

        NewPCG returns a new PCG seeded with the given values.

        func (*PCG) MarshalBinary

        func (p *PCG) MarshalBinary() ([]byte, error)

        MarshalBinary implements the encoding.BinaryMarshaler interface.

        func (*PCG) Seed

        func (p *PCG) Seed(seed1, seed2 uint64)

        Seed resets the PCG to behave the same way as NewPCG(seed1, seed2).

        func (*PCG) Uint64

        func (p *PCG) Uint64() uint64

        Uint64 return a uniformly-distributed random uint64 value.

        func (*PCG) UnmarshalBinary

        func (p *PCG) UnmarshalBinary(data []byte) error

        UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

        type Rand

        A Rand is a source of random numbers.

        type Rand struct {
            // contains filtered or unexported fields
        }
        

        func New

        func New(src Source) *Rand

        New returns a new Rand that uses random values from src to generate other random values.

        func (*Rand) ExpFloat64

        func (r *Rand) ExpFloat64() float64

        ExpFloat64 returns an exponentially distributed float64 in the range (0, +math.MaxFloat64] with an exponential distribution whose rate parameter (lambda) is 1 and whose mean is 1/lambda (1). To produce a distribution with a different rate parameter, callers can adjust the output using:

        sample = ExpFloat64() / desiredRateParameter
        

        func (*Rand) Float32

        func (r *Rand) Float32() float32

        Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0).

        func (*Rand) Float64

        func (r *Rand) Float64() float64

        Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0).

        func (*Rand) Int

        func (r *Rand) Int() int

        Int returns a non-negative pseudo-random int.

        func (*Rand) Int32

        func (r *Rand) Int32() int32

        Int32 returns a non-negative pseudo-random 31-bit integer as an int32.

        func (*Rand) Int32N

        func (r *Rand) Int32N(n int32) int32

        Int32N returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

        func (*Rand) Int64

        func (r *Rand) Int64() int64

        Int64 returns a non-negative pseudo-random 63-bit integer as an int64.

        func (*Rand) Int64N

        func (r *Rand) Int64N(n int64) int64

        Int64N returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

        func (*Rand) IntN

        func (r *Rand) IntN(n int) int

        IntN returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

        func (*Rand) NormFloat64

        func (r *Rand) NormFloat64() float64

        NormFloat64 returns a normally distributed float64 in the range -math.MaxFloat64 through +math.MaxFloat64 inclusive, with standard normal distribution (mean = 0, stddev = 1). To produce a different normal distribution, callers can adjust the output using:

        sample = NormFloat64() * desiredStdDev + desiredMean
        

        func (*Rand) Perm

        func (r *Rand) Perm(n int) []int

        Perm returns, as a slice of n ints, a pseudo-random permutation of the integers in the half-open interval [0,n).

        func (*Rand) Shuffle

        func (r *Rand) Shuffle(n int, swap func(i, j int))

        Shuffle pseudo-randomizes the order of elements. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.

        func (*Rand) Uint32

        func (r *Rand) Uint32() uint32

        Uint32 returns a pseudo-random 32-bit value as a uint32.

        func (*Rand) Uint32N

        func (r *Rand) Uint32N(n uint32) uint32

        Uint32N returns, as a uint32, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n == 0.

        func (*Rand) Uint64

        func (r *Rand) Uint64() uint64

        Uint64 returns a pseudo-random 64-bit value as a uint64.

        func (*Rand) Uint64N

        func (r *Rand) Uint64N(n uint64) uint64

        Uint64N returns, as a uint64, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n == 0.

        func (*Rand) UintN

        func (r *Rand) UintN(n uint) uint

        UintN returns, as a uint, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n == 0.

        type Source

        A Source is a source of uniformly-distributed pseudo-random uint64 values in the range [0, 1<<64).

        A Source is not safe for concurrent use by multiple goroutines.

        type Source interface {
            Uint64() uint64
        }

        type Zipf

        A Zipf generates Zipf distributed variates.

        type Zipf struct {
            // contains filtered or unexported fields
        }
        

        func NewZipf

        func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf

        NewZipf returns a Zipf variate generator. The generator generates values k ∈ [0, imax] such that P(k) is proportional to (v + k) ** (-s). Requirements: s > 1 and v >= 1.

        func (*Zipf) Uint64

        func (z *Zipf) Uint64() uint64

        Uint64 returns a value drawn from the Zipf distribution described by the Zipf object.

        mime - Go Documentation Server
        ...

        Package mime

        Overview ▾

        Package mime implements parts of the MIME spec.

        Constants

        const (
            // BEncoding represents Base64 encoding scheme as defined by RFC 2045.
            BEncoding = WordEncoder('b')
            // QEncoding represents the Q-encoding scheme as defined by RFC 2047.
            QEncoding = WordEncoder('q')
        )

        Variables

        ErrInvalidMediaParameter is returned by ParseMediaType if the media type value was found but there was an error parsing the optional parameters

        var ErrInvalidMediaParameter = errors.New("mime: invalid media parameter")

        func AddExtensionType

        func AddExtensionType(ext, typ string) error

        AddExtensionType sets the MIME type associated with the extension ext to typ. The extension should begin with a leading dot, as in ".html".

        func ExtensionsByType

        func ExtensionsByType(typ string) ([]string, error)

        ExtensionsByType returns the extensions known to be associated with the MIME type typ. The returned extensions will each begin with a leading dot, as in ".html". When typ has no associated extensions, ExtensionsByType returns an nil slice.

        func FormatMediaType

        func FormatMediaType(t string, param map[string]string) string

        FormatMediaType serializes mediatype t and the parameters param as a media type conforming to RFC 2045 and RFC 2616. The type and parameter names are written in lower-case. When any of the arguments result in a standard violation then FormatMediaType returns the empty string.

        Example

        Code:

        mediatype := "text/html"
        params := map[string]string{
            "charset": "utf-8",
        }
        
        result := mime.FormatMediaType(mediatype, params)
        
        fmt.Println("result:", result)
        

        Output:

        result: text/html; charset=utf-8
        

        func ParseMediaType

        func ParseMediaType(v string) (mediatype string, params map[string]string, err error)

        ParseMediaType parses a media type value and any optional parameters, per RFC 1521. Media types are the values in Content-Type and Content-Disposition headers (RFC 2183). On success, ParseMediaType returns the media type converted to lowercase and trimmed of white space and a non-nil map. If there is an error parsing the optional parameter, the media type will be returned along with the error ErrInvalidMediaParameter. The returned map, params, maps from the lowercase attribute to the attribute value with its case preserved.

        Example

        Code:

        mediatype, params, err := mime.ParseMediaType("text/html; charset=utf-8")
        if err != nil {
            panic(err)
        }
        
        fmt.Println("type:", mediatype)
        fmt.Println("charset:", params["charset"])
        

        Output:

        type: text/html
        charset: utf-8
        

        func TypeByExtension

        func TypeByExtension(ext string) string

        TypeByExtension returns the MIME type associated with the file extension ext. The extension ext should begin with a leading dot, as in ".html". When ext has no associated type, TypeByExtension returns "".

        Extensions are looked up first case-sensitively, then case-insensitively.

        The built-in table is small but on unix it is augmented by the local system's MIME-info database or mime.types file(s) if available under one or more of these names:

        /usr/local/share/mime/globs2
        /usr/share/mime/globs2
        /etc/mime.types
        /etc/apache2/mime.types
        /etc/apache/mime.types
        

        On Windows, MIME types are extracted from the registry.

        Text types have the charset parameter set to "utf-8" by default.

        type WordDecoder

        A WordDecoder decodes MIME headers containing RFC 2047 encoded-words.

        type WordDecoder struct {
            // CharsetReader, if non-nil, defines a function to generate
            // charset-conversion readers, converting from the provided
            // charset into UTF-8.
            // Charsets are always lower-case. utf-8, iso-8859-1 and us-ascii charsets
            // are handled by default.
            // One of the CharsetReader's result values must be non-nil.
            CharsetReader func(charset string, input io.Reader) (io.Reader, error)
        }
        

        func (*WordDecoder) Decode

        func (d *WordDecoder) Decode(word string) (string, error)

        Decode decodes an RFC 2047 encoded-word.

        Example

        Code:

        dec := new(mime.WordDecoder)
        header, err := dec.Decode("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=")
        if err != nil {
            panic(err)
        }
        fmt.Println(header)
        
        dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
            switch charset {
            case "x-case":
                // Fake character set for example.
                // Real use would integrate with packages such
                // as code.google.com/p/go-charset
                content, err := io.ReadAll(input)
                if err != nil {
                    return nil, err
                }
                return bytes.NewReader(bytes.ToUpper(content)), nil
            default:
                return nil, fmt.Errorf("unhandled charset %q", charset)
            }
        }
        header, err = dec.Decode("=?x-case?q?hello!?=")
        if err != nil {
            panic(err)
        }
        fmt.Println(header)
        

        Output:

        ¡Hola, señor!
        HELLO!
        

        func (*WordDecoder) DecodeHeader

        func (d *WordDecoder) DecodeHeader(header string) (string, error)

        DecodeHeader decodes all encoded-words of the given string. It returns an error if and only if CharsetReader of d returns an error.

        Example

        Code:

        dec := new(mime.WordDecoder)
        header, err := dec.DecodeHeader("=?utf-8?q?=C3=89ric?= <eric@example.org>, =?utf-8?q?Ana=C3=AFs?= <anais@example.org>")
        if err != nil {
            panic(err)
        }
        fmt.Println(header)
        
        header, err = dec.DecodeHeader("=?utf-8?q?=C2=A1Hola,?= =?utf-8?q?_se=C3=B1or!?=")
        if err != nil {
            panic(err)
        }
        fmt.Println(header)
        
        dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
            switch charset {
            case "x-case":
                // Fake character set for example.
                // Real use would integrate with packages such
                // as code.google.com/p/go-charset
                content, err := io.ReadAll(input)
                if err != nil {
                    return nil, err
                }
                return bytes.NewReader(bytes.ToUpper(content)), nil
            default:
                return nil, fmt.Errorf("unhandled charset %q", charset)
            }
        }
        header, err = dec.DecodeHeader("=?x-case?q?hello_?= =?x-case?q?world!?=")
        if err != nil {
            panic(err)
        }
        fmt.Println(header)
        

        Output:

        Éric <eric@example.org>, Anaïs <anais@example.org>
        ¡Hola, señor!
        HELLO WORLD!
        

        type WordEncoder

        A WordEncoder is an RFC 2047 encoded-word encoder.

        type WordEncoder byte

        func (WordEncoder) Encode

        func (e WordEncoder) Encode(charset, s string) string

        Encode returns the encoded-word form of s. If s is ASCII without special characters, it is returned unchanged. The provided charset is the IANA charset name of s. It is case insensitive.

        Example

        Code:

        fmt.Println(mime.QEncoding.Encode("utf-8", "¡Hola, señor!"))
        fmt.Println(mime.QEncoding.Encode("utf-8", "Hello!"))
        fmt.Println(mime.BEncoding.Encode("UTF-8", "¡Hola, señor!"))
        fmt.Println(mime.QEncoding.Encode("ISO-8859-1", "Caf\xE9"))
        

        Output:

        =?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=
        Hello!
        =?UTF-8?b?wqFIb2xhLCBzZcOxb3Ih?=
        =?ISO-8859-1?q?Caf=E9?=
        

        Subdirectories

        Name Synopsis
        ..
        multipart Package multipart implements MIME multipart parsing, as defined in RFC 2046.
        quotedprintable Package quotedprintable implements quoted-printable encoding as specified by RFC 2045.
        multipart - Go Documentation Server
        ...

        Package multipart

        import "mime/multipart"
        Overview
        Index
        Examples

        Overview ▾

        Package multipart implements MIME multipart parsing, as defined in RFC 2046.

        The implementation is sufficient for HTTP (RFC 2388) and the multipart bodies generated by popular browsers.

        Limits

        To protect against malicious inputs, this package sets limits on the size of the MIME data it processes.

        Reader.NextPart and Reader.NextRawPart limit the number of headers in a part to 10000 and Reader.ReadForm limits the total number of headers in all FileHeaders to 10000. These limits may be adjusted with the GODEBUG=multipartmaxheaders=<values> setting.

        Reader.ReadForm further limits the number of parts in a form to 1000. This limit may be adjusted with the GODEBUG=multipartmaxparts=<value> setting.

        Copyright 2023 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

        Variables

        ErrMessageTooLarge is returned by ReadForm if the message form data is too large to be processed.

        var ErrMessageTooLarge = errors.New("multipart: message too large")

        type File

        File is an interface to access the file part of a multipart message. Its contents may be either stored in memory or on disk. If stored on disk, the File's underlying concrete type will be an *os.File.

        type File interface {
            io.Reader
            io.ReaderAt
            io.Seeker
            io.Closer
        }

        type FileHeader

        A FileHeader describes a file part of a multipart request.

        type FileHeader struct {
            Filename string
            Header   textproto.MIMEHeader
            Size     int64
            // contains filtered or unexported fields
        }
        

        func (*FileHeader) Open

        func (fh *FileHeader) Open() (File, error)

        Open opens and returns the FileHeader's associated File.

        type Form

        Form is a parsed multipart form. Its File parts are stored either in memory or on disk, and are accessible via the *FileHeader's Open method. Its Value parts are stored as strings. Both are keyed by field name.

        type Form struct {
            Value map[string][]string
            File  map[string][]*FileHeader
        }
        

        func (*Form) RemoveAll

        func (f *Form) RemoveAll() error

        RemoveAll removes any temporary files associated with a Form.

        type Part

        A Part represents a single part in a multipart body.

        type Part struct {
            // The headers of the body, if any, with the keys canonicalized
            // in the same fashion that the Go http.Request headers are.
            // For example, "foo-bar" changes case to "Foo-Bar"
            Header textproto.MIMEHeader
            // contains filtered or unexported fields
        }
        

        func (*Part) Close

        func (p *Part) Close() error

        func (*Part) FileName

        func (p *Part) FileName() string

        FileName returns the filename parameter of the Part's Content-Disposition header. If not empty, the filename is passed through filepath.Base (which is platform dependent) before being returned.

        func (*Part) FormName

        func (p *Part) FormName() string

        FormName returns the name parameter if p has a Content-Disposition of type "form-data". Otherwise it returns the empty string.

        func (*Part) Read

        func (p *Part) Read(d []byte) (n int, err error)

        Read reads the body of a part, after its headers and before the next part (if any) begins.

        type Reader

        Reader is an iterator over parts in a MIME multipart body. Reader's underlying parser consumes its input as needed. Seeking isn't supported.

        type Reader struct {
            // contains filtered or unexported fields
        }
        

        func NewReader

        func NewReader(r io.Reader, boundary string) *Reader

        NewReader creates a new multipart Reader reading from r using the given MIME boundary.

        The boundary is usually obtained from the "boundary" parameter of the message's "Content-Type" header. Use mime.ParseMediaType to parse such headers.

        Example

        Code:

        msg := &mail.Message{
            Header: map[string][]string{
                "Content-Type": {"multipart/mixed; boundary=foo"},
            },
            Body: strings.NewReader(
                "--foo\r\nFoo: one\r\n\r\nA section\r\n" +
                    "--foo\r\nFoo: two\r\n\r\nAnd another\r\n" +
                    "--foo--\r\n"),
        }
        mediaType, params, err := mime.ParseMediaType(msg.Header.Get("Content-Type"))
        if err != nil {
            log.Fatal(err)
        }
        if strings.HasPrefix(mediaType, "multipart/") {
            mr := multipart.NewReader(msg.Body, params["boundary"])
            for {
                p, err := mr.NextPart()
                if err == io.EOF {
                    return
                }
                if err != nil {
                    log.Fatal(err)
                }
                slurp, err := io.ReadAll(p)
                if err != nil {
                    log.Fatal(err)
                }
                fmt.Printf("Part %q: %q\n", p.Header.Get("Foo"), slurp)
            }
        }
        
        

        Output:

        Part "one": "A section"
        Part "two": "And another"
        

        func (*Reader) NextPart

        func (r *Reader) NextPart() (*Part, error)

        NextPart returns the next part in the multipart or an error. When there are no more parts, the error io.EOF is returned.

        As a special case, if the "Content-Transfer-Encoding" header has a value of "quoted-printable", that header is instead hidden and the body is transparently decoded during Read calls.

        func (*Reader) NextRawPart

        func (r *Reader) NextRawPart() (*Part, error)

        NextRawPart returns the next part in the multipart or an error. When there are no more parts, the error io.EOF is returned.

        Unlike NextPart, it does not have special handling for "Content-Transfer-Encoding: quoted-printable".

        func (*Reader) ReadForm

        func (r *Reader) ReadForm(maxMemory int64) (*Form, error)

        ReadForm parses an entire multipart message whose parts have a Content-Disposition of "form-data". It stores up to maxMemory bytes + 10MB (reserved for non-file parts) in memory. File parts which can't be stored in memory will be stored on disk in temporary files. It returns ErrMessageTooLarge if all non-file parts can't be stored in memory.

        type Writer

        A Writer generates multipart messages.

        type Writer struct {
            // contains filtered or unexported fields
        }
        

        func NewWriter

        func NewWriter(w io.Writer) *Writer

        NewWriter returns a new multipart Writer with a random boundary, writing to w.

        func (*Writer) Boundary

        func (w *Writer) Boundary() string

        Boundary returns the Writer's boundary.

        func (*Writer) Close

        func (w *Writer) Close() error

        Close finishes the multipart message and writes the trailing boundary end line to the output.

        func (*Writer) CreateFormField

        func (w *Writer) CreateFormField(fieldname string) (io.Writer, error)

        CreateFormField calls CreatePart with a header using the given field name.

        func (*Writer) CreateFormFile

        func (w *Writer) CreateFormFile(fieldname, filename string) (io.Writer, error)

        CreateFormFile is a convenience wrapper around CreatePart. It creates a new form-data header with the provided field name and file name.

        func (*Writer) CreatePart

        func (w *Writer) CreatePart(header textproto.MIMEHeader) (io.Writer, error)

        CreatePart creates a new multipart section with the provided header. The body of the part should be written to the returned Writer. After calling CreatePart, any previous part may no longer be written to.

        func (*Writer) FormDataContentType

        func (w *Writer) FormDataContentType() string

        FormDataContentType returns the Content-Type for an HTTP multipart/form-data with this Writer's Boundary.

        func (*Writer) SetBoundary

        func (w *Writer) SetBoundary(boundary string) error

        SetBoundary overrides the Writer's default randomly-generated boundary separator with an explicit value.

        SetBoundary must be called before any parts are created, may only contain certain ASCII characters, and must be non-empty and at most 70 bytes long.

        func (*Writer) WriteField

        func (w *Writer) WriteField(fieldname, value string) error

        WriteField calls CreateFormField and then writes the given value.

        quotedprintable - Go Documentation Server
        ...

        Package quotedprintable

        import "mime/quotedprintable"
        Overview
        Index
        Examples

        Overview ▾

        Package quotedprintable implements quoted-printable encoding as specified by RFC 2045.

        type Reader

        Reader is a quoted-printable decoder.

        type Reader struct {
            // contains filtered or unexported fields
        }
        

        func NewReader

        func NewReader(r io.Reader) *Reader

        NewReader returns a quoted-printable reader, decoding from r.

        Example

        Code:

        for _, s := range []string{
            `=48=65=6C=6C=6F=2C=20=47=6F=70=68=65=72=73=21`,
            `invalid escape: <b style="font-size: 200%">hello</b>`,
            "Hello, Gophers! This symbol will be unescaped: =3D and this will be written in =\r\none line.",
        } {
            b, err := io.ReadAll(quotedprintable.NewReader(strings.NewReader(s)))
            fmt.Printf("%s %v\n", b, err)
        }
        

        Output:

        Hello, Gophers! <nil>
        invalid escape: <b style="font-size: 200%">hello</b> <nil>
        Hello, Gophers! This symbol will be unescaped: = and this will be written in one line. <nil>
        

        func (*Reader) Read

        func (r *Reader) Read(p []byte) (n int, err error)

        Read reads and decodes quoted-printable data from the underlying reader.

        type Writer

        A Writer is a quoted-printable writer that implements io.WriteCloser.

        type Writer struct {
            // Binary mode treats the writer's input as pure binary and processes end of
            // line bytes as binary data.
            Binary bool
            // contains filtered or unexported fields
        }
        

        func NewWriter

        func NewWriter(w io.Writer) *Writer

        NewWriter returns a new Writer that writes to w.

        Example

        Code:

        w := quotedprintable.NewWriter(os.Stdout)
        w.Write([]byte("These symbols will be escaped: = \t"))
        w.Close()
        
        

        Output:

        These symbols will be escaped: =3D =09
        

        func (*Writer) Close

        func (w *Writer) Close() error

        Close closes the Writer, flushing any unwritten data to the underlying io.Writer, but does not close the underlying io.Writer.

        func (*Writer) Write

        func (w *Writer) Write(p []byte) (n int, err error)

        Write encodes p using quoted-printable encoding and writes it to the underlying io.Writer. It limits line length to 76 characters. The encoded bytes are not necessarily flushed until the Writer is closed.

        net - Go Documentation Server
        ...

        Package net

        Overview ▾

        Package net provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.

        Although the package provides access to low-level networking primitives, most clients will need only the basic interface provided by the Dial, Listen, and Accept functions and the associated Conn and Listener interfaces. The crypto/tls package uses the same interfaces and similar Dial and Listen functions.

        The Dial function connects to a server:

        conn, err := net.Dial("tcp", "golang.org:80")
        if err != nil {
        	// handle error
        }
        fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
        status, err := bufio.NewReader(conn).ReadString('\n')
        // ...
        

        The Listen function creates servers:

        ln, err := net.Listen("tcp", ":8080")
        if err != nil {
        	// handle error
        }
        for {
        	conn, err := ln.Accept()
        	if err != nil {
        		// handle error
        	}
        	go handleConnection(conn)
        }
        

        Name Resolution

        The method for resolving domain names, whether indirectly with functions like Dial or directly with functions like LookupHost and LookupAddr, varies by operating system.

        On Unix systems, the resolver has two options for resolving names. It can use a pure Go resolver that sends DNS requests directly to the servers listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C library routines such as getaddrinfo and getnameinfo.

        By default the pure Go resolver is used, because a blocked DNS request consumes only a goroutine, while a blocked C call consumes an operating system thread. When cgo is available, the cgo-based resolver is used instead under a variety of conditions: on systems that do not let programs make direct DNS requests (OS X), when the LOCALDOMAIN environment variable is present (even if empty), when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, when the ASR_CONFIG environment variable is non-empty (OpenBSD only), when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the Go resolver does not implement, and when the name being looked up ends in .local or is an mDNS name.

        The resolver decision can be overridden by setting the netdns value of the GODEBUG environment variable (see package runtime) to go or cgo, as in:

        export GODEBUG=netdns=go    # force pure Go resolver
        export GODEBUG=netdns=cgo   # force native resolver (cgo, win32)
        

        The decision can also be forced while building the Go source tree by setting the netgo or netcgo build tag.

        A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver to print debugging information about its decisions. To force a particular resolver while also printing debugging information, join the two settings by a plus sign, as in GODEBUG=netdns=go+1.

        On macOS, if Go code that uses the net package is built with -buildmode=c-archive, linking the resulting archive into a C program requires passing -lresolv when linking the C code.

        On Plan 9, the resolver always accesses /net/cs and /net/dns.

        On Windows, in Go 1.18.x and earlier, the resolver always used C library functions, such as GetAddrInfo and DnsQuery.

        Index ▾

        Constants
        Variables
        func JoinHostPort(host, port string) string
        func LookupAddr(addr string) (names []string, err error)
        func LookupCNAME(host string) (cname string, err error)
        func LookupHost(host string) (addrs []string, err error)
        func LookupPort(network, service string) (port int, err error)
        func LookupTXT(name string) ([]string, error)
        func ParseCIDR(s string) (IP, *IPNet, error)
        func Pipe() (Conn, Conn)
        func SplitHostPort(hostport string) (host, port string, err error)
        type Addr
            func InterfaceAddrs() ([]Addr, error)
        type AddrError
            func (e *AddrError) Error() string
            func (e *AddrError) Temporary() bool
            func (e *AddrError) Timeout() bool
        type Buffers
            func (v *Buffers) Read(p []byte) (n int, err error)
            func (v *Buffers) WriteTo(w io.Writer) (n int64, err error)
        type Conn
            func Dial(network, address string) (Conn, error)
            func DialTimeout(network, address string, timeout time.Duration) (Conn, error)
            func FileConn(f *os.File) (c Conn, err error)
        type DNSConfigError
            func (e *DNSConfigError) Error() string
            func (e *DNSConfigError) Temporary() bool
            func (e *DNSConfigError) Timeout() bool
            func (e *DNSConfigError) Unwrap() error
        type DNSError
            func (e *DNSError) Error() string
            func (e *DNSError) Temporary() bool
            func (e *DNSError) Timeout() bool
        type Dialer
            func (d *Dialer) Dial(network, address string) (Conn, error)
            func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn, error)
            func (d *Dialer) MultipathTCP() bool
            func (d *Dialer) SetMultipathTCP(use bool)
        type Error
        type Flags
            func (f Flags) String() string
        type HardwareAddr
            func ParseMAC(s string) (hw HardwareAddr, err error)
            func (a HardwareAddr) String() string
        type IP
            func IPv4(a, b, c, d byte) IP
            func LookupIP(host string) ([]IP, error)
            func ParseIP(s string) IP
            func (ip IP) DefaultMask() IPMask
            func (ip IP) Equal(x IP) bool
            func (ip IP) IsGlobalUnicast() bool
            func (ip IP) IsInterfaceLocalMulticast() bool
            func (ip IP) IsLinkLocalMulticast() bool
            func (ip IP) IsLinkLocalUnicast() bool
            func (ip IP) IsLoopback() bool
            func (ip IP) IsMulticast() bool
            func (ip IP) IsPrivate() bool
            func (ip IP) IsUnspecified() bool
            func (ip IP) MarshalText() ([]byte, error)
            func (ip IP) Mask(mask IPMask) IP
            func (ip IP) String() string
            func (ip IP) To16() IP
            func (ip IP) To4() IP
            func (ip *IP) UnmarshalText(text []byte) error
        type IPAddr
            func ResolveIPAddr(network, address string) (*IPAddr, error)
            func (a *IPAddr) Network() string
            func (a *IPAddr) String() string
        type IPConn
            func DialIP(network string, laddr, raddr *IPAddr) (*IPConn, error)
            func ListenIP(network string, laddr *IPAddr) (*IPConn, error)
            func (c *IPConn) Close() error
            func (c *IPConn) File() (f *os.File, err error)
            func (c *IPConn) LocalAddr() Addr
            func (c *IPConn) Read(b []byte) (int, error)
            func (c *IPConn) ReadFrom(b []byte) (int, Addr, error)
            func (c *IPConn) ReadFromIP(b []byte) (int, *IPAddr, error)
            func (c *IPConn) ReadMsgIP(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error)
            func (c *IPConn) RemoteAddr() Addr
            func (c *IPConn) SetDeadline(t time.Time) error
            func (c *IPConn) SetReadBuffer(bytes int) error
            func (c *IPConn) SetReadDeadline(t time.Time) error
            func (c *IPConn) SetWriteBuffer(bytes int) error
            func (c *IPConn) SetWriteDeadline(t time.Time) error
            func (c *IPConn) SyscallConn() (syscall.RawConn, error)
            func (c *IPConn) Write(b []byte) (int, error)
            func (c *IPConn) WriteMsgIP(b, oob []byte, addr *IPAddr) (n, oobn int, err error)
            func (c *IPConn) WriteTo(b []byte, addr Addr) (int, error)
            func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (int, error)
        type IPMask
            func CIDRMask(ones, bits int) IPMask
            func IPv4Mask(a, b, c, d byte) IPMask
            func (m IPMask) Size() (ones, bits int)
            func (m IPMask) String() string
        type IPNet
            func (n *IPNet) Contains(ip IP) bool
            func (n *IPNet) Network() string
            func (n *IPNet) String() string
        type Interface
            func InterfaceByIndex(index int) (*Interface, error)
            func InterfaceByName(name string) (*Interface, error)
            func Interfaces() ([]Interface, error)
            func (ifi *Interface) Addrs() ([]Addr, error)
            func (ifi *Interface) MulticastAddrs() ([]Addr, error)
        type InvalidAddrError
            func (e InvalidAddrError) Error() string
            func (e InvalidAddrError) Temporary() bool
            func (e InvalidAddrError) Timeout() bool
        type ListenConfig
            func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error)
            func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error)
            func (lc *ListenConfig) MultipathTCP() bool
            func (lc *ListenConfig) SetMultipathTCP(use bool)
        type Listener
            func FileListener(f *os.File) (ln Listener, err error)
            func Listen(network, address string) (Listener, error)
        type MX
            func LookupMX(name string) ([]*MX, error)
        type NS
            func LookupNS(name string) ([]*NS, error)
        type OpError
            func (e *OpError) Error() string
            func (e *OpError) Temporary() bool
            func (e *OpError) Timeout() bool
            func (e *OpError) Unwrap() error
        type PacketConn
            func FilePacketConn(f *os.File) (c PacketConn, err error)
            func ListenPacket(network, address string) (PacketConn, error)
        type ParseError
            func (e *ParseError) Error() string
            func (e *ParseError) Temporary() bool
            func (e *ParseError) Timeout() bool
        type Resolver
            func (r *Resolver) LookupAddr(ctx context.Context, addr string) ([]string, error)
            func (r *Resolver) LookupCNAME(ctx context.Context, host string) (string, error)
            func (r *Resolver) LookupHost(ctx context.Context, host string) (addrs []string, err error)
            func (r *Resolver) LookupIP(ctx context.Context, network, host string) ([]IP, error)
            func (r *Resolver) LookupIPAddr(ctx context.Context, host string) ([]IPAddr, error)
            func (r *Resolver) LookupMX(ctx context.Context, name string) ([]*MX, error)
            func (r *Resolver) LookupNS(ctx context.Context, name string) ([]*NS, error)
            func (r *Resolver) LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)
            func (r *Resolver) LookupPort(ctx context.Context, network, service string) (port int, err error)
            func (r *Resolver) LookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error)
            func (r *Resolver) LookupTXT(ctx context.Context, name string) ([]string, error)
        type SRV
            func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error)
        type TCPAddr
            func ResolveTCPAddr(network, address string) (*TCPAddr, error)
            func TCPAddrFromAddrPort(addr netip.AddrPort) *TCPAddr
            func (a *TCPAddr) AddrPort() netip.AddrPort
            func (a *TCPAddr) Network() string
            func (a *TCPAddr) String() string
        type TCPConn
            func DialTCP(network string, laddr, raddr *TCPAddr) (*TCPConn, error)
            func (c *TCPConn) Close() error
            func (c *TCPConn) CloseRead() error
            func (c *TCPConn) CloseWrite() error
            func (c *TCPConn) File() (f *os.File, err error)
            func (c *TCPConn) LocalAddr() Addr
            func (c *TCPConn) MultipathTCP() (bool, error)
            func (c *TCPConn) Read(b []byte) (int, error)
            func (c *TCPConn) ReadFrom(r io.Reader) (int64, error)
            func (c *TCPConn) RemoteAddr() Addr
            func (c *TCPConn) SetDeadline(t time.Time) error
            func (c *TCPConn) SetKeepAlive(keepalive bool) error
            func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error
            func (c *TCPConn) SetLinger(sec int) error
            func (c *TCPConn) SetNoDelay(noDelay bool) error
            func (c *TCPConn) SetReadBuffer(bytes int) error
            func (c *TCPConn) SetReadDeadline(t time.Time) error
            func (c *TCPConn) SetWriteBuffer(bytes int) error
            func (c *TCPConn) SetWriteDeadline(t time.Time) error
            func (c *TCPConn) SyscallConn() (syscall.RawConn, error)
            func (c *TCPConn) Write(b []byte) (int, error)
            func (c *TCPConn) WriteTo(w io.Writer) (int64, error)
        type TCPListener
            func ListenTCP(network string, laddr *TCPAddr) (*TCPListener, error)
            func (l *TCPListener) Accept() (Conn, error)
            func (l *TCPListener) AcceptTCP() (*TCPConn, error)
            func (l *TCPListener) Addr() Addr
            func (l *TCPListener) Close() error
            func (l *TCPListener) File() (f *os.File, err error)
            func (l *TCPListener) SetDeadline(t time.Time) error
            func (l *TCPListener) SyscallConn() (syscall.RawConn, error)
        type UDPAddr
            func ResolveUDPAddr(network, address string) (*UDPAddr, error)
            func UDPAddrFromAddrPort(addr netip.AddrPort) *UDPAddr
            func (a *UDPAddr) AddrPort() netip.AddrPort
            func (a *UDPAddr) Network() string
            func (a *UDPAddr) String() string
        type UDPConn
            func DialUDP(network string, laddr, raddr *UDPAddr) (*UDPConn, error)
            func ListenMulticastUDP(network string, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error)
            func ListenUDP(network string, laddr *UDPAddr) (*UDPConn, error)
            func (c *UDPConn) Close() error
            func (c *UDPConn) File() (f *os.File, err error)
            func (c *UDPConn) LocalAddr() Addr
            func (c *UDPConn) Read(b []byte) (int, error)
            func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error)
            func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error)
            func (c *UDPConn) ReadFromUDPAddrPort(b []byte) (n int, addr netip.AddrPort, err error)
            func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)
            func (c *UDPConn) ReadMsgUDPAddrPort(b, oob []byte) (n, oobn, flags int, addr netip.AddrPort, err error)
            func (c *UDPConn) RemoteAddr() Addr
            func (c *UDPConn) SetDeadline(t time.Time) error
            func (c *UDPConn) SetReadBuffer(bytes int) error
            func (c *UDPConn) SetReadDeadline(t time.Time) error
            func (c *UDPConn) SetWriteBuffer(bytes int) error
            func (c *UDPConn) SetWriteDeadline(t time.Time) error
            func (c *UDPConn) SyscallConn() (syscall.RawConn, error)
            func (c *UDPConn) Write(b []byte) (int, error)
            func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobn int, err error)
            func (c *UDPConn) WriteMsgUDPAddrPort(b, oob []byte, addr netip.AddrPort) (n, oobn int, err error)
            func (c *UDPConn) WriteTo(b []byte, addr Addr) (int, error)
            func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (int, error)
            func (c *UDPConn) WriteToUDPAddrPort(b []byte, addr netip.AddrPort) (int, error)
        type UnixAddr
            func ResolveUnixAddr(network, address string) (*UnixAddr, error)
            func (a *UnixAddr) Network() string
            func (a *UnixAddr) String() string
        type UnixConn
            func DialUnix(network string, laddr, raddr *UnixAddr) (*UnixConn, error)
            func ListenUnixgram(network string, laddr *UnixAddr) (*UnixConn, error)
            func (c *UnixConn) Close() error
            func (c *UnixConn) CloseRead() error
            func (c *UnixConn) CloseWrite() error
            func (c *UnixConn) File() (f *os.File, err error)
            func (c *UnixConn) LocalAddr() Addr
            func (c *UnixConn) Read(b []byte) (int, error)
            func (c *UnixConn) ReadFrom(b []byte) (int, Addr, error)
            func (c *UnixConn) ReadFromUnix(b []byte) (int, *UnixAddr, error)
            func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error)
            func (c *UnixConn) RemoteAddr() Addr
            func (c *UnixConn) SetDeadline(t time.Time) error
            func (c *UnixConn) SetReadBuffer(bytes int) error
            func (c *UnixConn) SetReadDeadline(t time.Time) error
            func (c *UnixConn) SetWriteBuffer(bytes int) error
            func (c *UnixConn) SetWriteDeadline(t time.Time) error
            func (c *UnixConn) SyscallConn() (syscall.RawConn, error)
            func (c *UnixConn) Write(b []byte) (int, error)
            func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err error)
            func (c *UnixConn) WriteTo(b []byte, addr Addr) (int, error)
            func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (int, error)
        type UnixListener
            func ListenUnix(network string, laddr *UnixAddr) (*UnixListener, error)
            func (l *UnixListener) Accept() (Conn, error)
            func (l *UnixListener) AcceptUnix() (*UnixConn, error)
            func (l *UnixListener) Addr() Addr
            func (l *UnixListener) Close() error
            func (l *UnixListener) File() (f *os.File, err error)
            func (l *UnixListener) SetDeadline(t time.Time) error
            func (l *UnixListener) SetUnlinkOnClose(unlink bool)
            func (l *UnixListener) SyscallConn() (syscall.RawConn, error)
        type UnknownNetworkError
            func (e UnknownNetworkError) Error() string
            func (e UnknownNetworkError) Temporary() bool
            func (e UnknownNetworkError) Timeout() bool
        Bugs

        Package files

        addrselect.go cgo_linux.go cgo_resnew.go cgo_socknew.go cgo_unix.go cgo_unix_cgo.go cgo_unix_cgo_res.go conf.go dial.go dnsclient.go dnsclient_unix.go dnsconfig.go dnsconfig_unix.go error_posix.go error_unix.go fd_posix.go fd_unix.go file.go file_unix.go hook.go hook_unix.go hosts.go interface.go interface_linux.go ip.go iprawsock.go iprawsock_posix.go ipsock.go ipsock_posix.go lookup.go lookup_unix.go mac.go mptcpsock_linux.go net.go netcgo_off.go netgo_off.go nss.go parse.go pipe.go port.go port_unix.go rawconn.go rlimit_unix.go sendfile_linux.go sock_cloexec.go sock_linux.go sock_posix.go sockaddr_posix.go sockopt_linux.go sockopt_posix.go sockoptip_linux.go sockoptip_posix.go splice_linux.go tcpsock.go tcpsock_posix.go tcpsockopt_posix.go tcpsockopt_unix.go udpsock.go udpsock_posix.go unixsock.go unixsock_posix.go unixsock_readmsg_cmsg_cloexec.go writev_unix.go

        Constants

        IP address lengths (bytes).

        const (
            IPv4len = 4
            IPv6len = 16
        )

        Variables

        Well-known IPv4 addresses

        var (
            IPv4bcast     = IPv4(255, 255, 255, 255) // limited broadcast
            IPv4allsys    = IPv4(224, 0, 0, 1)       // all systems
            IPv4allrouter = IPv4(224, 0, 0, 2)       // all routers
            IPv4zero      = IPv4(0, 0, 0, 0)         // all zeros
        )

        Well-known IPv6 addresses

        var (
            IPv6zero                   = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
            IPv6unspecified            = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
            IPv6loopback               = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
            IPv6interfacelocalallnodes = IP{0xff, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
            IPv6linklocalallnodes      = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
            IPv6linklocalallrouters    = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02}
        )

        DefaultResolver is the resolver used by the package-level Lookup functions and by Dialers without a specified Resolver.

        var DefaultResolver = &Resolver{}

        ErrClosed is the error returned by an I/O call on a network connection that has already been closed, or that is closed by another goroutine before the I/O is completed. This may be wrapped in another error, and should normally be tested using errors.Is(err, net.ErrClosed).

        var ErrClosed error = errClosed

        Various errors contained in OpError.

        var (
            ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection")
        )

        func JoinHostPort

        func JoinHostPort(host, port string) string

        JoinHostPort combines host and port into a network address of the form "host:port". If host contains a colon, as found in literal IPv6 addresses, then JoinHostPort returns "[host]:port".

        See func Dial for a description of the host and port parameters.

        func LookupAddr

        func LookupAddr(addr string) (names []string, err error)

        LookupAddr performs a reverse lookup for the given address, returning a list of names mapping to that address.

        The returned names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

        When using the host C library resolver, at most one result will be returned. To bypass the host resolver, use a custom Resolver.

        LookupAddr uses context.Background internally; to specify the context, use Resolver.LookupAddr.

        func LookupCNAME

        func LookupCNAME(host string) (cname string, err error)

        LookupCNAME returns the canonical name for the given host. Callers that do not care about the canonical name can call LookupHost or LookupIP directly; both take care of resolving the canonical name as part of the lookup.

        A canonical name is the final name after following zero or more CNAME records. LookupCNAME does not return an error if host does not contain DNS "CNAME" records, as long as host resolves to address records.

        The returned canonical name is validated to be a properly formatted presentation-format domain name.

        LookupCNAME uses context.Background internally; to specify the context, use Resolver.LookupCNAME.

        func LookupHost

        func LookupHost(host string) (addrs []string, err error)

        LookupHost looks up the given host using the local resolver. It returns a slice of that host's addresses.

        LookupHost uses context.Background internally; to specify the context, use Resolver.LookupHost.

        func LookupPort

        func LookupPort(network, service string) (port int, err error)

        LookupPort looks up the port for the given network and service.

        LookupPort uses context.Background internally; to specify the context, use Resolver.LookupPort.

        func LookupTXT

        func LookupTXT(name string) ([]string, error)

        LookupTXT returns the DNS TXT records for the given domain name.

        LookupTXT uses context.Background internally; to specify the context, use Resolver.LookupTXT.

        func ParseCIDR

        func ParseCIDR(s string) (IP, *IPNet, error)

        ParseCIDR parses s as a CIDR notation IP address and prefix length, like "192.0.2.0/24" or "2001:db8::/32", as defined in RFC 4632 and RFC 4291.

        It returns the IP address and the network implied by the IP and prefix length. For example, ParseCIDR("192.0.2.1/24") returns the IP address 192.0.2.1 and the network 192.0.2.0/24.

        Example

        Code:

        ipv4Addr, ipv4Net, err := net.ParseCIDR("192.0.2.1/24")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(ipv4Addr)
        fmt.Println(ipv4Net)
        
        ipv6Addr, ipv6Net, err := net.ParseCIDR("2001:db8:a0b:12f0::1/32")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(ipv6Addr)
        fmt.Println(ipv6Net)
        
        

        Output:

        192.0.2.1
        192.0.2.0/24
        2001:db8:a0b:12f0::1
        2001:db8::/32
        

        func Pipe

        func Pipe() (Conn, Conn)

        Pipe creates a synchronous, in-memory, full duplex network connection; both ends implement the Conn interface. Reads on one end are matched with writes on the other, copying data directly between the two; there is no internal buffering.

        func SplitHostPort

        func SplitHostPort(hostport string) (host, port string, err error)

        SplitHostPort splits a network address of the form "host:port", "host%zone:port", "[host]:port" or "[host%zone]:port" into host or host%zone and port.

        A literal IPv6 address in hostport must be enclosed in square brackets, as in "[::1]:80", "[::1%lo0]:80".

        See func Dial for a description of the hostport parameter, and host and port results.

        type Addr

        Addr represents a network end point address.

        The two methods [Addr.Network] and [Addr.String] conventionally return strings that can be passed as the arguments to Dial, but the exact form and meaning of the strings is up to the implementation.

        type Addr interface {
            Network() string // name of the network (for example, "tcp", "udp")
            String() string  // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80")
        }

        func InterfaceAddrs

        func InterfaceAddrs() ([]Addr, error)

        InterfaceAddrs returns a list of the system's unicast interface addresses.

        The returned list does not identify the associated interface; use Interfaces and Interface.Addrs for more detail.

        type AddrError

        type AddrError struct {
            Err  string
            Addr string
        }
        

        func (*AddrError) Error

        func (e *AddrError) Error() string

        func (*AddrError) Temporary

        func (e *AddrError) Temporary() bool

        func (*AddrError) Timeout

        func (e *AddrError) Timeout() bool

        type Buffers

        Buffers contains zero or more runs of bytes to write.

        On certain machines, for certain types of connections, this is optimized into an OS-specific batch write operation (such as "writev").

        type Buffers [][]byte

        func (*Buffers) Read

        func (v *Buffers) Read(p []byte) (n int, err error)

        Read from the buffers.

        Read implements io.Reader for Buffers.

        Read modifies the slice v as well as v[i] for 0 <= i < len(v), but does not modify v[i][j] for any i, j.

        func (*Buffers) WriteTo

        func (v *Buffers) WriteTo(w io.Writer) (n int64, err error)

        WriteTo writes contents of the buffers to w.

        WriteTo implements io.WriterTo for Buffers.

        WriteTo modifies the slice v as well as v[i] for 0 <= i < len(v), but does not modify v[i][j] for any i, j.

        type Conn

        Conn is a generic stream-oriented network connection.

        Multiple goroutines may invoke methods on a Conn simultaneously.

        type Conn interface {
            // Read reads data from the connection.
            // Read can be made to time out and return an error after a fixed
            // time limit; see SetDeadline and SetReadDeadline.
            Read(b []byte) (n int, err error)
        
            // Write writes data to the connection.
            // Write can be made to time out and return an error after a fixed
            // time limit; see SetDeadline and SetWriteDeadline.
            Write(b []byte) (n int, err error)
        
            // Close closes the connection.
            // Any blocked Read or Write operations will be unblocked and return errors.
            Close() error
        
            // LocalAddr returns the local network address, if known.
            LocalAddr() Addr
        
            // RemoteAddr returns the remote network address, if known.
            RemoteAddr() Addr
        
            // SetDeadline sets the read and write deadlines associated
            // with the connection. It is equivalent to calling both
            // SetReadDeadline and SetWriteDeadline.
            //
            // A deadline is an absolute time after which I/O operations
            // fail instead of blocking. The deadline applies to all future
            // and pending I/O, not just the immediately following call to
            // Read or Write. After a deadline has been exceeded, the
            // connection can be refreshed by setting a deadline in the future.
            //
            // If the deadline is exceeded a call to Read or Write or to other
            // I/O methods will return an error that wraps os.ErrDeadlineExceeded.
            // This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
            // The error's Timeout method will return true, but note that there
            // are other possible errors for which the Timeout method will
            // return true even if the deadline has not been exceeded.
            //
            // An idle timeout can be implemented by repeatedly extending
            // the deadline after successful Read or Write calls.
            //
            // A zero value for t means I/O operations will not time out.
            SetDeadline(t time.Time) error
        
            // SetReadDeadline sets the deadline for future Read calls
            // and any currently-blocked Read call.
            // A zero value for t means Read will not time out.
            SetReadDeadline(t time.Time) error
        
            // SetWriteDeadline sets the deadline for future Write calls
            // and any currently-blocked Write call.
            // Even if write times out, it may return n > 0, indicating that
            // some of the data was successfully written.
            // A zero value for t means Write will not time out.
            SetWriteDeadline(t time.Time) error
        }

        func Dial

        func Dial(network, address string) (Conn, error)

        Dial connects to the address on the named network.

        Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4" (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and "unixpacket".

        For TCP and UDP networks, the address has the form "host:port". The host must be a literal IP address, or a host name that can be resolved to IP addresses. The port must be a literal port number or a service name. If the host is a literal IPv6 address it must be enclosed in square brackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80". The zone specifies the scope of the literal IPv6 address as defined in RFC 4007. The functions JoinHostPort and SplitHostPort manipulate a pair of host and port in this form. When using TCP, and the host resolves to multiple IP addresses, Dial will try each IP address in order until one succeeds.

        Examples:

        Dial("tcp", "golang.org:http")
        Dial("tcp", "192.0.2.1:http")
        Dial("tcp", "198.51.100.1:80")
        Dial("udp", "[2001:db8::1]:domain")
        Dial("udp", "[fe80::1%lo0]:53")
        Dial("tcp", ":80")
        

        For IP networks, the network must be "ip", "ip4" or "ip6" followed by a colon and a literal protocol number or a protocol name, and the address has the form "host". The host must be a literal IP address or a literal IPv6 address with zone. It depends on each operating system how the operating system behaves with a non-well known protocol number such as "0" or "255".

        Examples:

        Dial("ip4:1", "192.0.2.1")
        Dial("ip6:ipv6-icmp", "2001:db8::1")
        Dial("ip6:58", "fe80::1%lo0")
        

        For TCP, UDP and IP networks, if the host is empty or a literal unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for TCP and UDP, "", "0.0.0.0" or "::" for IP, the local system is assumed.

        For Unix networks, the address must be a file system path.

        func DialTimeout

        func DialTimeout(network, address string, timeout time.Duration) (Conn, error)

        DialTimeout acts like Dial but takes a timeout.

        The timeout includes name resolution, if required. When using TCP, and the host in the address parameter resolves to multiple IP addresses, the timeout is spread over each consecutive dial, such that each is given an appropriate fraction of the time to connect.

        See func Dial for a description of the network and address parameters.

        func FileConn

        func FileConn(f *os.File) (c Conn, err error)

        FileConn returns a copy of the network connection corresponding to the open file f. It is the caller's responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.

        type DNSConfigError

        DNSConfigError represents an error reading the machine's DNS configuration. (No longer used; kept for compatibility.)

        type DNSConfigError struct {
            Err error
        }
        

        func (*DNSConfigError) Error

        func (e *DNSConfigError) Error() string

        func (*DNSConfigError) Temporary

        func (e *DNSConfigError) Temporary() bool

        func (*DNSConfigError) Timeout

        func (e *DNSConfigError) Timeout() bool

        func (*DNSConfigError) Unwrap

        func (e *DNSConfigError) Unwrap() error

        type DNSError

        DNSError represents a DNS lookup error.

        type DNSError struct {
            Err         string // description of the error
            Name        string // name looked for
            Server      string // server used
            IsTimeout   bool   // if true, timed out; not all timeouts set this
            IsTemporary bool   // if true, error is temporary; not all errors set this
        
            // IsNotFound is set to true when the requested name does not
            // contain any records of the requested type (data not found),
            // or the name itself was not found (NXDOMAIN).
            IsNotFound bool
        }
        

        func (*DNSError) Error

        func (e *DNSError) Error() string

        func (*DNSError) Temporary

        func (e *DNSError) Temporary() bool

        Temporary reports whether the DNS error is known to be temporary. This is not always known; a DNS lookup may fail due to a temporary error and return a DNSError for which Temporary returns false.

        func (*DNSError) Timeout

        func (e *DNSError) Timeout() bool

        Timeout reports whether the DNS lookup is known to have timed out. This is not always known; a DNS lookup may fail due to a timeout and return a DNSError for which Timeout returns false.

        type Dialer

        A Dialer contains options for connecting to an address.

        The zero value for each field is equivalent to dialing without that option. Dialing with the zero value of Dialer is therefore equivalent to just calling the Dial function.

        It is safe to call Dialer's methods concurrently.

        type Dialer struct {
            // Timeout is the maximum amount of time a dial will wait for
            // a connect to complete. If Deadline is also set, it may fail
            // earlier.
            //
            // The default is no timeout.
            //
            // When using TCP and dialing a host name with multiple IP
            // addresses, the timeout may be divided between them.
            //
            // With or without a timeout, the operating system may impose
            // its own earlier timeout. For instance, TCP timeouts are
            // often around 3 minutes.
            Timeout time.Duration
        
            // Deadline is the absolute point in time after which dials
            // will fail. If Timeout is set, it may fail earlier.
            // Zero means no deadline, or dependent on the operating system
            // as with the Timeout option.
            Deadline time.Time
        
            // LocalAddr is the local address to use when dialing an
            // address. The address must be of a compatible type for the
            // network being dialed.
            // If nil, a local address is automatically chosen.
            LocalAddr Addr
        
            // DualStack previously enabled RFC 6555 Fast Fallback
            // support, also known as "Happy Eyeballs", in which IPv4 is
            // tried soon if IPv6 appears to be misconfigured and
            // hanging.
            //
            // Deprecated: Fast Fallback is enabled by default. To
            // disable, set FallbackDelay to a negative value.
            DualStack bool
        
            // FallbackDelay specifies the length of time to wait before
            // spawning a RFC 6555 Fast Fallback connection. That is, this
            // is the amount of time to wait for IPv6 to succeed before
            // assuming that IPv6 is misconfigured and falling back to
            // IPv4.
            //
            // If zero, a default delay of 300ms is used.
            // A negative value disables Fast Fallback support.
            FallbackDelay time.Duration
        
            // KeepAlive specifies the interval between keep-alive
            // probes for an active network connection.
            // If zero, keep-alive probes are sent with a default value
            // (currently 15 seconds), if supported by the protocol and operating
            // system. Network protocols or operating systems that do
            // not support keep-alives ignore this field.
            // If negative, keep-alive probes are disabled.
            KeepAlive time.Duration
        
            // Resolver optionally specifies an alternate resolver to use.
            Resolver *Resolver
        
            // Cancel is an optional channel whose closure indicates that
            // the dial should be canceled. Not all types of dials support
            // cancellation.
            //
            // Deprecated: Use DialContext instead.
            Cancel <-chan struct{}
        
            // If Control is not nil, it is called after creating the network
            // connection but before actually dialing.
            //
            // Network and address parameters passed to Control function are not
            // necessarily the ones passed to Dial. For example, passing "tcp" to Dial
            // will cause the Control function to be called with "tcp4" or "tcp6".
            //
            // Control is ignored if ControlContext is not nil.
            Control func(network, address string, c syscall.RawConn) error
        
            // If ControlContext is not nil, it is called after creating the network
            // connection but before actually dialing.
            //
            // Network and address parameters passed to ControlContext function are not
            // necessarily the ones passed to Dial. For example, passing "tcp" to Dial
            // will cause the ControlContext function to be called with "tcp4" or "tcp6".
            //
            // If ControlContext is not nil, Control is ignored.
            ControlContext func(ctx context.Context, network, address string, c syscall.RawConn) error
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        var d net.Dialer
        ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
        defer cancel()
        
        conn, err := d.DialContext(ctx, "tcp", "localhost:12345")
        if err != nil {
            log.Fatalf("Failed to dial: %v", err)
        }
        defer conn.Close()
        
        if _, err := conn.Write([]byte("Hello, World!")); err != nil {
            log.Fatal(err)
        }
        

        Example (Unix)

        Code:

        // DialUnix does not take a context.Context parameter. This example shows
        // how to dial a Unix socket with a Context. Note that the Context only
        // applies to the dial operation; it does not apply to the connection once
        // it has been established.
        var d net.Dialer
        ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
        defer cancel()
        
        d.LocalAddr = nil // if you have a local addr, add it here
        raddr := net.UnixAddr{Name: "/path/to/unix.sock", Net: "unix"}
        conn, err := d.DialContext(ctx, "unix", raddr.String())
        if err != nil {
            log.Fatalf("Failed to dial: %v", err)
        }
        defer conn.Close()
        if _, err := conn.Write([]byte("Hello, socket!")); err != nil {
            log.Fatal(err)
        }
        

        func (*Dialer) Dial

        func (d *Dialer) Dial(network, address string) (Conn, error)

        Dial connects to the address on the named network.

        See func Dial for a description of the network and address parameters.

        Dial uses context.Background internally; to specify the context, use Dialer.DialContext.

        func (*Dialer) DialContext

        func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn, error)

        DialContext connects to the address on the named network using the provided context.

        The provided Context must be non-nil. If the context expires before the connection is complete, an error is returned. Once successfully connected, any expiration of the context will not affect the connection.

        When using TCP, and the host in the address parameter resolves to multiple network addresses, any dial timeout (from d.Timeout or ctx) is spread over each consecutive dial, such that each is given an appropriate fraction of the time to connect. For example, if a host has 4 IP addresses and the timeout is 1 minute, the connect to each single address will be given 15 seconds to complete before trying the next one.

        See func Dial for a description of the network and address parameters.

        func (*Dialer) MultipathTCP

        func (d *Dialer) MultipathTCP() bool

        MultipathTCP reports whether MPTCP will be used.

        This method doesn't check if MPTCP is supported by the operating system or not.

        func (*Dialer) SetMultipathTCP

        func (d *Dialer) SetMultipathTCP(use bool)

        SetMultipathTCP directs the Dial methods to use, or not use, MPTCP, if supported by the operating system. This method overrides the system default and the GODEBUG=multipathtcp=... setting if any.

        If MPTCP is not available on the host or not supported by the server, the Dial methods will fall back to TCP.

        type Error

        An Error represents a network error.

        type Error interface {
            error
            Timeout() bool // Is the error a timeout?
        
            // Deprecated: Temporary errors are not well-defined.
            // Most "temporary" errors are timeouts, and the few exceptions are surprising.
            // Do not use this method.
            Temporary() bool
        }

        type Flags

        type Flags uint
        const (
            FlagUp           Flags = 1 << iota // interface is administratively up
            FlagBroadcast                      // interface supports broadcast access capability
            FlagLoopback                       // interface is a loopback interface
            FlagPointToPoint                   // interface belongs to a point-to-point link
            FlagMulticast                      // interface supports multicast access capability
            FlagRunning                        // interface is in running state
        )

        func (Flags) String

        func (f Flags) String() string

        type HardwareAddr

        A HardwareAddr represents a physical hardware address.

        type HardwareAddr []byte

        func ParseMAC

        func ParseMAC(s string) (hw HardwareAddr, err error)

        ParseMAC parses s as an IEEE 802 MAC-48, EUI-48, EUI-64, or a 20-octet IP over InfiniBand link-layer address using one of the following formats:

        00:00:5e:00:53:01
        02:00:5e:10:00:00:00:01
        00:00:00:00:fe:80:00:00:00:00:00:00:02:00:5e:10:00:00:00:01
        00-00-5e-00-53-01
        02-00-5e-10-00-00-00-01
        00-00-00-00-fe-80-00-00-00-00-00-00-02-00-5e-10-00-00-00-01
        0000.5e00.5301
        0200.5e10.0000.0001
        0000.0000.fe80.0000.0000.0000.0200.5e10.0000.0001
        

        func (HardwareAddr) String

        func (a HardwareAddr) String() string

        type IP

        An IP is a single IP address, a slice of bytes. Functions in this package accept either 4-byte (IPv4) or 16-byte (IPv6) slices as input.

        Note that in this documentation, referring to an IP address as an IPv4 address or an IPv6 address is a semantic property of the address, not just the length of the byte slice: a 16-byte slice can still be an IPv4 address.

        type IP []byte

        Example (To4)

        Code:

        ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
        ipv4 := net.IPv4(10, 255, 0, 0)
        
        fmt.Println(ipv6.To4())
        fmt.Println(ipv4.To4())
        
        

        Output:

        <nil>
        10.255.0.0
        

        func IPv4

        func IPv4(a, b, c, d byte) IP

        IPv4 returns the IP address (in 16-byte form) of the IPv4 address a.b.c.d.

        Example

        Code:

        fmt.Println(net.IPv4(8, 8, 8, 8))
        
        

        Output:

        8.8.8.8
        

        func LookupIP

        func LookupIP(host string) ([]IP, error)

        LookupIP looks up host using the local resolver. It returns a slice of that host's IPv4 and IPv6 addresses.

        func ParseIP

        func ParseIP(s string) IP

        ParseIP parses s as an IP address, returning the result. The string s can be in IPv4 dotted decimal ("192.0.2.1"), IPv6 ("2001:db8::68"), or IPv4-mapped IPv6 ("::ffff:192.0.2.1") form. If s is not a valid textual representation of an IP address, ParseIP returns nil.

        Example

        Code:

        fmt.Println(net.ParseIP("192.0.2.1"))
        fmt.Println(net.ParseIP("2001:db8::68"))
        fmt.Println(net.ParseIP("192.0.2"))
        
        

        Output:

        192.0.2.1
        2001:db8::68
        <nil>
        

        func (IP) DefaultMask

        func (ip IP) DefaultMask() IPMask

        DefaultMask returns the default IP mask for the IP address ip. Only IPv4 addresses have default masks; DefaultMask returns nil if ip is not a valid IPv4 address.

        Example

        Code:

        ip := net.ParseIP("192.0.2.1")
        fmt.Println(ip.DefaultMask())
        
        

        Output:

        ffffff00
        

        func (IP) Equal

        func (ip IP) Equal(x IP) bool

        Equal reports whether ip and x are the same IP address. An IPv4 address and that same address in IPv6 form are considered to be equal.

        Example

        Code:

        ipv4DNS := net.ParseIP("8.8.8.8")
        ipv4Lo := net.ParseIP("127.0.0.1")
        ipv6DNS := net.ParseIP("0:0:0:0:0:FFFF:0808:0808")
        
        fmt.Println(ipv4DNS.Equal(ipv4DNS))
        fmt.Println(ipv4DNS.Equal(ipv4Lo))
        fmt.Println(ipv4DNS.Equal(ipv6DNS))
        
        

        Output:

        true
        false
        true
        

        func (IP) IsGlobalUnicast

        func (ip IP) IsGlobalUnicast() bool

        IsGlobalUnicast reports whether ip is a global unicast address.

        The identification of global unicast addresses uses address type identification as defined in RFC 1122, RFC 4632 and RFC 4291 with the exception of IPv4 directed broadcast addresses. It returns true even if ip is in IPv4 private address space or local IPv6 unicast address space.

        Example

        Code:

        ipv6Global := net.ParseIP("2000::")
        ipv6UniqLocal := net.ParseIP("2000::")
        ipv6Multi := net.ParseIP("FF00::")
        
        ipv4Private := net.ParseIP("10.255.0.0")
        ipv4Public := net.ParseIP("8.8.8.8")
        ipv4Broadcast := net.ParseIP("255.255.255.255")
        
        fmt.Println(ipv6Global.IsGlobalUnicast())
        fmt.Println(ipv6UniqLocal.IsGlobalUnicast())
        fmt.Println(ipv6Multi.IsGlobalUnicast())
        
        fmt.Println(ipv4Private.IsGlobalUnicast())
        fmt.Println(ipv4Public.IsGlobalUnicast())
        fmt.Println(ipv4Broadcast.IsGlobalUnicast())
        
        

        Output:

        true
        true
        false
        true
        true
        false
        

        func (IP) IsInterfaceLocalMulticast

        func (ip IP) IsInterfaceLocalMulticast() bool

        IsInterfaceLocalMulticast reports whether ip is an interface-local multicast address.

        Example

        Code:

        ipv6InterfaceLocalMulti := net.ParseIP("ff01::1")
        ipv6Global := net.ParseIP("2000::")
        ipv4 := net.ParseIP("255.0.0.0")
        
        fmt.Println(ipv6InterfaceLocalMulti.IsInterfaceLocalMulticast())
        fmt.Println(ipv6Global.IsInterfaceLocalMulticast())
        fmt.Println(ipv4.IsInterfaceLocalMulticast())
        
        

        Output:

        true
        false
        false
        

        func (IP) IsLinkLocalMulticast

        func (ip IP) IsLinkLocalMulticast() bool

        IsLinkLocalMulticast reports whether ip is a link-local multicast address.

        Example

        Code:

        ipv6LinkLocalMulti := net.ParseIP("ff02::2")
        ipv6LinkLocalUni := net.ParseIP("fe80::")
        ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")
        ipv4LinkLocalUni := net.ParseIP("169.254.0.0")
        
        fmt.Println(ipv6LinkLocalMulti.IsLinkLocalMulticast())
        fmt.Println(ipv6LinkLocalUni.IsLinkLocalMulticast())
        fmt.Println(ipv4LinkLocalMulti.IsLinkLocalMulticast())
        fmt.Println(ipv4LinkLocalUni.IsLinkLocalMulticast())
        
        

        Output:

        true
        false
        true
        false
        

        func (IP) IsLinkLocalUnicast

        func (ip IP) IsLinkLocalUnicast() bool

        IsLinkLocalUnicast reports whether ip is a link-local unicast address.

        Example

        Code:

        ipv6LinkLocalUni := net.ParseIP("fe80::")
        ipv6Global := net.ParseIP("2000::")
        ipv4LinkLocalUni := net.ParseIP("169.254.0.0")
        ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")
        
        fmt.Println(ipv6LinkLocalUni.IsLinkLocalUnicast())
        fmt.Println(ipv6Global.IsLinkLocalUnicast())
        fmt.Println(ipv4LinkLocalUni.IsLinkLocalUnicast())
        fmt.Println(ipv4LinkLocalMulti.IsLinkLocalUnicast())
        
        

        Output:

        true
        false
        true
        false
        

        func (IP) IsLoopback

        func (ip IP) IsLoopback() bool

        IsLoopback reports whether ip is a loopback address.

        Example

        Code:

        ipv6Lo := net.ParseIP("::1")
        ipv6 := net.ParseIP("ff02::1")
        ipv4Lo := net.ParseIP("127.0.0.0")
        ipv4 := net.ParseIP("128.0.0.0")
        
        fmt.Println(ipv6Lo.IsLoopback())
        fmt.Println(ipv6.IsLoopback())
        fmt.Println(ipv4Lo.IsLoopback())
        fmt.Println(ipv4.IsLoopback())
        
        

        Output:

        true
        false
        true
        false
        

        func (IP) IsMulticast

        func (ip IP) IsMulticast() bool

        IsMulticast reports whether ip is a multicast address.

        Example

        Code:

        ipv6Multi := net.ParseIP("FF00::")
        ipv6LinkLocalMulti := net.ParseIP("ff02::1")
        ipv6Lo := net.ParseIP("::1")
        ipv4Multi := net.ParseIP("239.0.0.0")
        ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")
        ipv4Lo := net.ParseIP("127.0.0.0")
        
        fmt.Println(ipv6Multi.IsMulticast())
        fmt.Println(ipv6LinkLocalMulti.IsMulticast())
        fmt.Println(ipv6Lo.IsMulticast())
        fmt.Println(ipv4Multi.IsMulticast())
        fmt.Println(ipv4LinkLocalMulti.IsMulticast())
        fmt.Println(ipv4Lo.IsMulticast())
        
        

        Output:

        true
        true
        false
        true
        true
        false
        

        func (IP) IsPrivate

        func (ip IP) IsPrivate() bool

        IsPrivate reports whether ip is a private address, according to RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses).

        Example

        Code:

        ipv6Private := net.ParseIP("fc00::")
        ipv6Public := net.ParseIP("fe00::")
        ipv4Private := net.ParseIP("10.255.0.0")
        ipv4Public := net.ParseIP("11.0.0.0")
        
        fmt.Println(ipv6Private.IsPrivate())
        fmt.Println(ipv6Public.IsPrivate())
        fmt.Println(ipv4Private.IsPrivate())
        fmt.Println(ipv4Public.IsPrivate())
        
        

        Output:

        true
        false
        true
        false
        

        func (IP) IsUnspecified

        func (ip IP) IsUnspecified() bool

        IsUnspecified reports whether ip is an unspecified address, either the IPv4 address "0.0.0.0" or the IPv6 address "::".

        Example

        Code:

        ipv6Unspecified := net.ParseIP("::")
        ipv6Specified := net.ParseIP("fe00::")
        ipv4Unspecified := net.ParseIP("0.0.0.0")
        ipv4Specified := net.ParseIP("8.8.8.8")
        
        fmt.Println(ipv6Unspecified.IsUnspecified())
        fmt.Println(ipv6Specified.IsUnspecified())
        fmt.Println(ipv4Unspecified.IsUnspecified())
        fmt.Println(ipv4Specified.IsUnspecified())
        
        

        Output:

        true
        false
        true
        false
        

        func (IP) MarshalText

        func (ip IP) MarshalText() ([]byte, error)

        MarshalText implements the encoding.TextMarshaler interface. The encoding is the same as returned by IP.String, with one exception: When len(ip) is zero, it returns an empty slice.

        func (IP) Mask

        func (ip IP) Mask(mask IPMask) IP

        Mask returns the result of masking the IP address ip with mask.

        Example

        Code:

        ipv4Addr := net.ParseIP("192.0.2.1")
        // This mask corresponds to a /24 subnet for IPv4.
        ipv4Mask := net.CIDRMask(24, 32)
        fmt.Println(ipv4Addr.Mask(ipv4Mask))
        
        ipv6Addr := net.ParseIP("2001:db8:a0b:12f0::1")
        // This mask corresponds to a /32 subnet for IPv6.
        ipv6Mask := net.CIDRMask(32, 128)
        fmt.Println(ipv6Addr.Mask(ipv6Mask))
        
        

        Output:

        192.0.2.0
        2001:db8::
        

        func (IP) String

        func (ip IP) String() string

        String returns the string form of the IP address ip. It returns one of 4 forms:

        • "<nil>", if ip has length 0
        • dotted decimal ("192.0.2.1"), if ip is an IPv4 or IP4-mapped IPv6 address
        • IPv6 conforming to RFC 5952 ("2001:db8::1"), if ip is a valid IPv6 address
        • the hexadecimal form of ip, without punctuation, if no other cases apply

        Example

        Code:

        ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
        ipv4 := net.IPv4(10, 255, 0, 0)
        
        fmt.Println(ipv6.String())
        fmt.Println(ipv4.String())
        
        

        Output:

        fc00::
        10.255.0.0
        

        func (IP) To16

        func (ip IP) To16() IP

        To16 converts the IP address ip to a 16-byte representation. If ip is not an IP address (it is the wrong length), To16 returns nil.

        Example

        Code:

        ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
        ipv4 := net.IPv4(10, 255, 0, 0)
        
        fmt.Println(ipv6.To16())
        fmt.Println(ipv4.To16())
        
        

        Output:

        fc00::
        10.255.0.0
        

        func (IP) To4

        func (ip IP) To4() IP

        To4 converts the IPv4 address ip to a 4-byte representation. If ip is not an IPv4 address, To4 returns nil.

        func (*IP) UnmarshalText

        func (ip *IP) UnmarshalText(text []byte) error

        UnmarshalText implements the encoding.TextUnmarshaler interface. The IP address is expected in a form accepted by ParseIP.

        type IPAddr

        IPAddr represents the address of an IP end point.

        type IPAddr struct {
            IP   IP
            Zone string // IPv6 scoped addressing zone
        }
        

        func ResolveIPAddr

        func ResolveIPAddr(network, address string) (*IPAddr, error)

        ResolveIPAddr returns an address of IP end point.

        The network must be an IP network name.

        If the host in the address parameter is not a literal IP address, ResolveIPAddr resolves the address to an address of IP end point. Otherwise, it parses the address as a literal IP address. The address parameter can use a host name, but this is not recommended, because it will return at most one of the host name's IP addresses.

        See func Dial for a description of the network and address parameters.

        func (*IPAddr) Network

        func (a *IPAddr) Network() string

        Network returns the address's network name, "ip".

        func (*IPAddr) String

        func (a *IPAddr) String() string

        type IPConn

        IPConn is the implementation of the Conn and PacketConn interfaces for IP network connections.

        type IPConn struct {
            // contains filtered or unexported fields
        }
        

        func DialIP

        func DialIP(network string, laddr, raddr *IPAddr) (*IPConn, error)

        DialIP acts like Dial for IP networks.

        The network must be an IP network name; see func Dial for details.

        If laddr is nil, a local address is automatically chosen. If the IP field of raddr is nil or an unspecified IP address, the local system is assumed.

        func ListenIP

        func ListenIP(network string, laddr *IPAddr) (*IPConn, error)

        ListenIP acts like ListenPacket for IP networks.

        The network must be an IP network name; see func Dial for details.

        If the IP field of laddr is nil or an unspecified IP address, ListenIP listens on all available IP addresses of the local system except multicast IP addresses.

        func (*IPConn) Close

        func (c *IPConn) Close() error

        Close closes the connection.

        func (*IPConn) File

        func (c *IPConn) File() (f *os.File, err error)

        File returns a copy of the underlying os.File. It is the caller's responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.

        The returned os.File's file descriptor is different from the connection's. Attempting to change properties of the original using this duplicate may or may not have the desired effect.

        func (*IPConn) LocalAddr

        func (c *IPConn) LocalAddr() Addr

        LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.

        func (*IPConn) Read

        func (c *IPConn) Read(b []byte) (int, error)

        Read implements the Conn Read method.

        func (*IPConn) ReadFrom

        func (c *IPConn) ReadFrom(b []byte) (int, Addr, error)

        ReadFrom implements the PacketConn ReadFrom method.

        func (*IPConn) ReadFromIP

        func (c *IPConn) ReadFromIP(b []byte) (int, *IPAddr, error)

        ReadFromIP acts like ReadFrom but returns an IPAddr.

        func (*IPConn) ReadMsgIP

        func (c *IPConn) ReadMsgIP(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error)

        ReadMsgIP reads a message from c, copying the payload into b and the associated out-of-band data into oob. It returns the number of bytes copied into b, the number of bytes copied into oob, the flags that were set on the message and the source address of the message.

        The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

        func (*IPConn) RemoteAddr

        func (c *IPConn) RemoteAddr() Addr

        RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.

        func (*IPConn) SetDeadline

        func (c *IPConn) SetDeadline(t time.Time) error

        SetDeadline implements the Conn SetDeadline method.

        func (*IPConn) SetReadBuffer

        func (c *IPConn) SetReadBuffer(bytes int) error

        SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

        func (*IPConn) SetReadDeadline

        func (c *IPConn) SetReadDeadline(t time.Time) error

        SetReadDeadline implements the Conn SetReadDeadline method.

        func (*IPConn) SetWriteBuffer

        func (c *IPConn) SetWriteBuffer(bytes int) error

        SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

        func (*IPConn) SetWriteDeadline

        func (c *IPConn) SetWriteDeadline(t time.Time) error

        SetWriteDeadline implements the Conn SetWriteDeadline method.

        func (*IPConn) SyscallConn

        func (c *IPConn) SyscallConn() (syscall.RawConn, error)

        SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

        func (*IPConn) Write

        func (c *IPConn) Write(b []byte) (int, error)

        Write implements the Conn Write method.

        func (*IPConn) WriteMsgIP

        func (c *IPConn) WriteMsgIP(b, oob []byte, addr *IPAddr) (n, oobn int, err error)

        WriteMsgIP writes a message to addr via c, copying the payload from b and the associated out-of-band data from oob. It returns the number of payload and out-of-band bytes written.

        The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

        func (*IPConn) WriteTo

        func (c *IPConn) WriteTo(b []byte, addr Addr) (int, error)

        WriteTo implements the PacketConn WriteTo method.

        func (*IPConn) WriteToIP

        func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (int, error)

        WriteToIP acts like IPConn.WriteTo but takes an IPAddr.

        type IPMask

        An IPMask is a bitmask that can be used to manipulate IP addresses for IP addressing and routing.

        See type IPNet and func ParseCIDR for details.

        type IPMask []byte

        func CIDRMask

        func CIDRMask(ones, bits int) IPMask

        CIDRMask returns an IPMask consisting of 'ones' 1 bits followed by 0s up to a total length of 'bits' bits. For a mask of this form, CIDRMask is the inverse of IPMask.Size.

        Example

        Code:

        // This mask corresponds to a /31 subnet for IPv4.
        fmt.Println(net.CIDRMask(31, 32))
        
        // This mask corresponds to a /64 subnet for IPv6.
        fmt.Println(net.CIDRMask(64, 128))
        
        

        Output:

        fffffffe
        ffffffffffffffff0000000000000000
        

        func IPv4Mask

        func IPv4Mask(a, b, c, d byte) IPMask

        IPv4Mask returns the IP mask (in 4-byte form) of the IPv4 mask a.b.c.d.

        Example

        Code:

        fmt.Println(net.IPv4Mask(255, 255, 255, 0))
        
        

        Output:

        ffffff00
        

        func (IPMask) Size

        func (m IPMask) Size() (ones, bits int)

        Size returns the number of leading ones and total bits in the mask. If the mask is not in the canonical form--ones followed by zeros--then Size returns 0, 0.

        func (IPMask) String

        func (m IPMask) String() string

        String returns the hexadecimal form of m, with no punctuation.

        type IPNet

        An IPNet represents an IP network.

        type IPNet struct {
            IP   IP     // network number
            Mask IPMask // network mask
        }
        

        func (*IPNet) Contains

        func (n *IPNet) Contains(ip IP) bool

        Contains reports whether the network includes ip.

        func (*IPNet) Network

        func (n *IPNet) Network() string

        Network returns the address's network name, "ip+net".

        func (*IPNet) String

        func (n *IPNet) String() string

        String returns the CIDR notation of n like "192.0.2.0/24" or "2001:db8::/48" as defined in RFC 4632 and RFC 4291. If the mask is not in the canonical form, it returns the string which consists of an IP address, followed by a slash character and a mask expressed as hexadecimal form with no punctuation like "198.51.100.0/c000ff00".

        type Interface

        Interface represents a mapping between network interface name and index. It also represents network interface facility information.

        type Interface struct {
            Index        int          // positive integer that starts at one, zero is never used
            MTU          int          // maximum transmission unit
            Name         string       // e.g., "en0", "lo0", "eth0.100"
            HardwareAddr HardwareAddr // IEEE MAC-48, EUI-48 and EUI-64 form
            Flags        Flags        // e.g., FlagUp, FlagLoopback, FlagMulticast
        }
        

        func InterfaceByIndex

        func InterfaceByIndex(index int) (*Interface, error)

        InterfaceByIndex returns the interface specified by index.

        On Solaris, it returns one of the logical network interfaces sharing the logical data link; for more precision use InterfaceByName.

        func InterfaceByName

        func InterfaceByName(name string) (*Interface, error)

        InterfaceByName returns the interface specified by name.

        func Interfaces

        func Interfaces() ([]Interface, error)

        Interfaces returns a list of the system's network interfaces.

        func (*Interface) Addrs

        func (ifi *Interface) Addrs() ([]Addr, error)

        Addrs returns a list of unicast interface addresses for a specific interface.

        func (*Interface) MulticastAddrs

        func (ifi *Interface) MulticastAddrs() ([]Addr, error)

        MulticastAddrs returns a list of multicast, joined group addresses for a specific interface.

        type InvalidAddrError

        type InvalidAddrError string

        func (InvalidAddrError) Error

        func (e InvalidAddrError) Error() string

        func (InvalidAddrError) Temporary

        func (e InvalidAddrError) Temporary() bool

        func (InvalidAddrError) Timeout

        func (e InvalidAddrError) Timeout() bool

        type ListenConfig

        ListenConfig contains options for listening to an address.

        type ListenConfig struct {
            // If Control is not nil, it is called after creating the network
            // connection but before binding it to the operating system.
            //
            // Network and address parameters passed to Control method are not
            // necessarily the ones passed to Listen. For example, passing "tcp" to
            // Listen will cause the Control function to be called with "tcp4" or "tcp6".
            Control func(network, address string, c syscall.RawConn) error
        
            // KeepAlive specifies the keep-alive period for network
            // connections accepted by this listener.
            // If zero, keep-alives are enabled if supported by the protocol
            // and operating system. Network protocols or operating systems
            // that do not support keep-alives ignore this field.
            // If negative, keep-alives are disabled.
            KeepAlive time.Duration
            // contains filtered or unexported fields
        }
        

        func (*ListenConfig) Listen

        func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error)

        Listen announces on the local network address.

        See func Listen for a description of the network and address parameters.

        func (*ListenConfig) ListenPacket

        func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error)

        ListenPacket announces on the local network address.

        See func ListenPacket for a description of the network and address parameters.

        func (*ListenConfig) MultipathTCP

        func (lc *ListenConfig) MultipathTCP() bool

        MultipathTCP reports whether MPTCP will be used.

        This method doesn't check if MPTCP is supported by the operating system or not.

        func (*ListenConfig) SetMultipathTCP

        func (lc *ListenConfig) SetMultipathTCP(use bool)

        SetMultipathTCP directs the Listen method to use, or not use, MPTCP, if supported by the operating system. This method overrides the system default and the GODEBUG=multipathtcp=... setting if any.

        If MPTCP is not available on the host or not supported by the client, the Listen method will fall back to TCP.

        type Listener

        A Listener is a generic network listener for stream-oriented protocols.

        Multiple goroutines may invoke methods on a Listener simultaneously.

        type Listener interface {
            // Accept waits for and returns the next connection to the listener.
            Accept() (Conn, error)
        
            // Close closes the listener.
            // Any blocked Accept operations will be unblocked and return errors.
            Close() error
        
            // Addr returns the listener's network address.
            Addr() Addr
        }

        Example

        Code:

        // Listen on TCP port 2000 on all available unicast and
        // anycast IP addresses of the local system.
        l, err := net.Listen("tcp", ":2000")
        if err != nil {
            log.Fatal(err)
        }
        defer l.Close()
        for {
            // Wait for a connection.
            conn, err := l.Accept()
            if err != nil {
                log.Fatal(err)
            }
            // Handle the connection in a new goroutine.
            // The loop then returns to accepting, so that
            // multiple connections may be served concurrently.
            go func(c net.Conn) {
                // Echo all incoming data.
                io.Copy(c, c)
                // Shut down the connection.
                c.Close()
            }(conn)
        }
        

        func FileListener

        func FileListener(f *os.File) (ln Listener, err error)

        FileListener returns a copy of the network listener corresponding to the open file f. It is the caller's responsibility to close ln when finished. Closing ln does not affect f, and closing f does not affect ln.

        func Listen

        func Listen(network, address string) (Listener, error)

        Listen announces on the local network address.

        The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket".

        For TCP networks, if the host in the address parameter is empty or a literal unspecified IP address, Listen listens on all available unicast and anycast IP addresses of the local system. To only use IPv4, use network "tcp4". The address can use a host name, but this is not recommended, because it will create a listener for at most one of the host's IP addresses. If the port in the address parameter is empty or "0", as in "127.0.0.1:" or "[::1]:0", a port number is automatically chosen. The Addr method of Listener can be used to discover the chosen port.

        See func Dial for a description of the network and address parameters.

        Listen uses context.Background internally; to specify the context, use ListenConfig.Listen.

        type MX

        An MX represents a single DNS MX record.

        type MX struct {
            Host string
            Pref uint16
        }
        

        func LookupMX

        func LookupMX(name string) ([]*MX, error)

        LookupMX returns the DNS MX records for the given domain name sorted by preference.

        The returned mail server names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

        LookupMX uses context.Background internally; to specify the context, use Resolver.LookupMX.

        type NS

        An NS represents a single DNS NS record.

        type NS struct {
            Host string
        }
        

        func LookupNS

        func LookupNS(name string) ([]*NS, error)

        LookupNS returns the DNS NS records for the given domain name.

        The returned name server names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

        LookupNS uses context.Background internally; to specify the context, use Resolver.LookupNS.

        type OpError

        OpError is the error type usually returned by functions in the net package. It describes the operation, network type, and address of an error.

        type OpError struct {
            // Op is the operation which caused the error, such as
            // "read" or "write".
            Op string
        
            // Net is the network type on which this error occurred,
            // such as "tcp" or "udp6".
            Net string
        
            // For operations involving a remote network connection, like
            // Dial, Read, or Write, Source is the corresponding local
            // network address.
            Source Addr
        
            // Addr is the network address for which this error occurred.
            // For local operations, like Listen or SetDeadline, Addr is
            // the address of the local endpoint being manipulated.
            // For operations involving a remote network connection, like
            // Dial, Read, or Write, Addr is the remote address of that
            // connection.
            Addr Addr
        
            // Err is the error that occurred during the operation.
            // The Error method panics if the error is nil.
            Err error
        }
        

        func (*OpError) Error

        func (e *OpError) Error() string

        func (*OpError) Temporary

        func (e *OpError) Temporary() bool

        func (*OpError) Timeout

        func (e *OpError) Timeout() bool

        func (*OpError) Unwrap

        func (e *OpError) Unwrap() error

        type PacketConn

        PacketConn is a generic packet-oriented network connection.

        Multiple goroutines may invoke methods on a PacketConn simultaneously.

        type PacketConn interface {
            // ReadFrom reads a packet from the connection,
            // copying the payload into p. It returns the number of
            // bytes copied into p and the return address that
            // was on the packet.
            // It returns the number of bytes read (0 <= n <= len(p))
            // and any error encountered. Callers should always process
            // the n > 0 bytes returned before considering the error err.
            // ReadFrom can be made to time out and return an error after a
            // fixed time limit; see SetDeadline and SetReadDeadline.
            ReadFrom(p []byte) (n int, addr Addr, err error)
        
            // WriteTo writes a packet with payload p to addr.
            // WriteTo can be made to time out and return an Error after a
            // fixed time limit; see SetDeadline and SetWriteDeadline.
            // On packet-oriented connections, write timeouts are rare.
            WriteTo(p []byte, addr Addr) (n int, err error)
        
            // Close closes the connection.
            // Any blocked ReadFrom or WriteTo operations will be unblocked and return errors.
            Close() error
        
            // LocalAddr returns the local network address, if known.
            LocalAddr() Addr
        
            // SetDeadline sets the read and write deadlines associated
            // with the connection. It is equivalent to calling both
            // SetReadDeadline and SetWriteDeadline.
            //
            // A deadline is an absolute time after which I/O operations
            // fail instead of blocking. The deadline applies to all future
            // and pending I/O, not just the immediately following call to
            // Read or Write. After a deadline has been exceeded, the
            // connection can be refreshed by setting a deadline in the future.
            //
            // If the deadline is exceeded a call to Read or Write or to other
            // I/O methods will return an error that wraps os.ErrDeadlineExceeded.
            // This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
            // The error's Timeout method will return true, but note that there
            // are other possible errors for which the Timeout method will
            // return true even if the deadline has not been exceeded.
            //
            // An idle timeout can be implemented by repeatedly extending
            // the deadline after successful ReadFrom or WriteTo calls.
            //
            // A zero value for t means I/O operations will not time out.
            SetDeadline(t time.Time) error
        
            // SetReadDeadline sets the deadline for future ReadFrom calls
            // and any currently-blocked ReadFrom call.
            // A zero value for t means ReadFrom will not time out.
            SetReadDeadline(t time.Time) error
        
            // SetWriteDeadline sets the deadline for future WriteTo calls
            // and any currently-blocked WriteTo call.
            // Even if write times out, it may return n > 0, indicating that
            // some of the data was successfully written.
            // A zero value for t means WriteTo will not time out.
            SetWriteDeadline(t time.Time) error
        }

        func FilePacketConn

        func FilePacketConn(f *os.File) (c PacketConn, err error)

        FilePacketConn returns a copy of the packet network connection corresponding to the open file f. It is the caller's responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.

        func ListenPacket

        func ListenPacket(network, address string) (PacketConn, error)

        ListenPacket announces on the local network address.

        The network must be "udp", "udp4", "udp6", "unixgram", or an IP transport. The IP transports are "ip", "ip4", or "ip6" followed by a colon and a literal protocol number or a protocol name, as in "ip:1" or "ip:icmp".

        For UDP and IP networks, if the host in the address parameter is empty or a literal unspecified IP address, ListenPacket listens on all available IP addresses of the local system except multicast IP addresses. To only use IPv4, use network "udp4" or "ip4:proto". The address can use a host name, but this is not recommended, because it will create a listener for at most one of the host's IP addresses. If the port in the address parameter is empty or "0", as in "127.0.0.1:" or "[::1]:0", a port number is automatically chosen. The LocalAddr method of PacketConn can be used to discover the chosen port.

        See func Dial for a description of the network and address parameters.

        ListenPacket uses context.Background internally; to specify the context, use ListenConfig.ListenPacket.

        type ParseError

        A ParseError is the error type of literal network address parsers.

        type ParseError struct {
            // Type is the type of string that was expected, such as
            // "IP address", "CIDR address".
            Type string
        
            // Text is the malformed text string.
            Text string
        }
        

        func (*ParseError) Error

        func (e *ParseError) Error() string

        func (*ParseError) Temporary

        func (e *ParseError) Temporary() bool

        func (*ParseError) Timeout

        func (e *ParseError) Timeout() bool

        type Resolver

        A Resolver looks up names and numbers.

        A nil *Resolver is equivalent to a zero Resolver.

        type Resolver struct {
            // PreferGo controls whether Go's built-in DNS resolver is preferred
            // on platforms where it's available. It is equivalent to setting
            // GODEBUG=netdns=go, but scoped to just this resolver.
            PreferGo bool
        
            // StrictErrors controls the behavior of temporary errors
            // (including timeout, socket errors, and SERVFAIL) when using
            // Go's built-in resolver. For a query composed of multiple
            // sub-queries (such as an A+AAAA address lookup, or walking the
            // DNS search list), this option causes such errors to abort the
            // whole query instead of returning a partial result. This is
            // not enabled by default because it may affect compatibility
            // with resolvers that process AAAA queries incorrectly.
            StrictErrors bool
        
            // Dial optionally specifies an alternate dialer for use by
            // Go's built-in DNS resolver to make TCP and UDP connections
            // to DNS services. The host in the address parameter will
            // always be a literal IP address and not a host name, and the
            // port in the address parameter will be a literal port number
            // and not a service name.
            // If the Conn returned is also a PacketConn, sent and received DNS
            // messages must adhere to RFC 1035 section 4.2.1, "UDP usage".
            // Otherwise, DNS messages transmitted over Conn must adhere
            // to RFC 7766 section 5, "Transport Protocol Selection".
            // If nil, the default dialer is used.
            Dial func(ctx context.Context, network, address string) (Conn, error)
            // contains filtered or unexported fields
        }
        

        func (*Resolver) LookupAddr

        func (r *Resolver) LookupAddr(ctx context.Context, addr string) ([]string, error)

        LookupAddr performs a reverse lookup for the given address, returning a list of names mapping to that address.

        The returned names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

        func (*Resolver) LookupCNAME

        func (r *Resolver) LookupCNAME(ctx context.Context, host string) (string, error)

        LookupCNAME returns the canonical name for the given host. Callers that do not care about the canonical name can call LookupHost or LookupIP directly; both take care of resolving the canonical name as part of the lookup.

        A canonical name is the final name after following zero or more CNAME records. LookupCNAME does not return an error if host does not contain DNS "CNAME" records, as long as host resolves to address records.

        The returned canonical name is validated to be a properly formatted presentation-format domain name.

        func (*Resolver) LookupHost

        func (r *Resolver) LookupHost(ctx context.Context, host string) (addrs []string, err error)

        LookupHost looks up the given host using the local resolver. It returns a slice of that host's addresses.

        func (*Resolver) LookupIP

        func (r *Resolver) LookupIP(ctx context.Context, network, host string) ([]IP, error)

        LookupIP looks up host for the given network using the local resolver. It returns a slice of that host's IP addresses of the type specified by network. network must be one of "ip", "ip4" or "ip6".

        func (*Resolver) LookupIPAddr

        func (r *Resolver) LookupIPAddr(ctx context.Context, host string) ([]IPAddr, error)

        LookupIPAddr looks up host using the local resolver. It returns a slice of that host's IPv4 and IPv6 addresses.

        func (*Resolver) LookupMX

        func (r *Resolver) LookupMX(ctx context.Context, name string) ([]*MX, error)

        LookupMX returns the DNS MX records for the given domain name sorted by preference.

        The returned mail server names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

        func (*Resolver) LookupNS

        func (r *Resolver) LookupNS(ctx context.Context, name string) ([]*NS, error)

        LookupNS returns the DNS NS records for the given domain name.

        The returned name server names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

        func (*Resolver) LookupNetIP

        func (r *Resolver) LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)

        LookupNetIP looks up host using the local resolver. It returns a slice of that host's IP addresses of the type specified by network. The network must be one of "ip", "ip4" or "ip6".

        func (*Resolver) LookupPort

        func (r *Resolver) LookupPort(ctx context.Context, network, service string) (port int, err error)

        LookupPort looks up the port for the given network and service.

        The network must be one of "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6" or "ip".

        func (*Resolver) LookupSRV

        func (r *Resolver) LookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error)

        LookupSRV tries to resolve an SRV query of the given service, protocol, and domain name. The proto is "tcp" or "udp". The returned records are sorted by priority and randomized by weight within a priority.

        LookupSRV constructs the DNS name to look up following RFC 2782. That is, it looks up _service._proto.name. To accommodate services publishing SRV records under non-standard names, if both service and proto are empty strings, LookupSRV looks up name directly.

        The returned service names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

        func (*Resolver) LookupTXT

        func (r *Resolver) LookupTXT(ctx context.Context, name string) ([]string, error)

        LookupTXT returns the DNS TXT records for the given domain name.

        type SRV

        An SRV represents a single DNS SRV record.

        type SRV struct {
            Target   string
            Port     uint16
            Priority uint16
            Weight   uint16
        }
        

        func LookupSRV

        func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error)

        LookupSRV tries to resolve an SRV query of the given service, protocol, and domain name. The proto is "tcp" or "udp". The returned records are sorted by priority and randomized by weight within a priority.

        LookupSRV constructs the DNS name to look up following RFC 2782. That is, it looks up _service._proto.name. To accommodate services publishing SRV records under non-standard names, if both service and proto are empty strings, LookupSRV looks up name directly.

        The returned service names are validated to be properly formatted presentation-format domain names. If the response contains invalid names, those records are filtered out and an error will be returned alongside the remaining results, if any.

        type TCPAddr

        TCPAddr represents the address of a TCP end point.

        type TCPAddr struct {
            IP   IP
            Port int
            Zone string // IPv6 scoped addressing zone
        }
        

        func ResolveTCPAddr

        func ResolveTCPAddr(network, address string) (*TCPAddr, error)

        ResolveTCPAddr returns an address of TCP end point.

        The network must be a TCP network name.

        If the host in the address parameter is not a literal IP address or the port is not a literal port number, ResolveTCPAddr resolves the address to an address of TCP end point. Otherwise, it parses the address as a pair of literal IP address and port number. The address parameter can use a host name, but this is not recommended, because it will return at most one of the host name's IP addresses.

        See func Dial for a description of the network and address parameters.

        func TCPAddrFromAddrPort

        func TCPAddrFromAddrPort(addr netip.AddrPort) *TCPAddr

        TCPAddrFromAddrPort returns addr as a TCPAddr. If addr.IsValid() is false, then the returned TCPAddr will contain a nil IP field, indicating an address family-agnostic unspecified address.

        func (*TCPAddr) AddrPort

        func (a *TCPAddr) AddrPort() netip.AddrPort

        AddrPort returns the TCPAddr a as a netip.AddrPort.

        If a.Port does not fit in a uint16, it's silently truncated.

        If a is nil, a zero value is returned.

        func (*TCPAddr) Network

        func (a *TCPAddr) Network() string

        Network returns the address's network name, "tcp".

        func (*TCPAddr) String

        func (a *TCPAddr) String() string

        type TCPConn

        TCPConn is an implementation of the Conn interface for TCP network connections.

        type TCPConn struct {
            // contains filtered or unexported fields
        }
        

        func DialTCP

        func DialTCP(network string, laddr, raddr *TCPAddr) (*TCPConn, error)

        DialTCP acts like Dial for TCP networks.

        The network must be a TCP network name; see func Dial for details.

        If laddr is nil, a local address is automatically chosen. If the IP field of raddr is nil or an unspecified IP address, the local system is assumed.

        func (*TCPConn) Close

        func (c *TCPConn) Close() error

        Close closes the connection.

        func (*TCPConn) CloseRead

        func (c *TCPConn) CloseRead() error

        CloseRead shuts down the reading side of the TCP connection. Most callers should just use Close.

        func (*TCPConn) CloseWrite

        func (c *TCPConn) CloseWrite() error

        CloseWrite shuts down the writing side of the TCP connection. Most callers should just use Close.

        func (*TCPConn) File

        func (c *TCPConn) File() (f *os.File, err error)

        File returns a copy of the underlying os.File. It is the caller's responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.

        The returned os.File's file descriptor is different from the connection's. Attempting to change properties of the original using this duplicate may or may not have the desired effect.

        func (*TCPConn) LocalAddr

        func (c *TCPConn) LocalAddr() Addr

        LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.

        func (*TCPConn) MultipathTCP

        func (c *TCPConn) MultipathTCP() (bool, error)

        MultipathTCP reports whether the ongoing connection is using MPTCP.

        If Multipath TCP is not supported by the host, by the other peer or intentionally / accidentally filtered out by a device in between, a fallback to TCP will be done. This method does its best to check if MPTCP is still being used or not.

        On Linux, more conditions are verified on kernels >= v5.16, improving the results.

        func (*TCPConn) Read

        func (c *TCPConn) Read(b []byte) (int, error)

        Read implements the Conn Read method.

        func (*TCPConn) ReadFrom

        func (c *TCPConn) ReadFrom(r io.Reader) (int64, error)

        ReadFrom implements the io.ReaderFrom ReadFrom method.

        func (*TCPConn) RemoteAddr

        func (c *TCPConn) RemoteAddr() Addr

        RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.

        func (*TCPConn) SetDeadline

        func (c *TCPConn) SetDeadline(t time.Time) error

        SetDeadline implements the Conn SetDeadline method.

        func (*TCPConn) SetKeepAlive

        func (c *TCPConn) SetKeepAlive(keepalive bool) error

        SetKeepAlive sets whether the operating system should send keep-alive messages on the connection.

        func (*TCPConn) SetKeepAlivePeriod

        func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error

        SetKeepAlivePeriod sets period between keep-alives.

        func (*TCPConn) SetLinger

        func (c *TCPConn) SetLinger(sec int) error

        SetLinger sets the behavior of Close on a connection which still has data waiting to be sent or to be acknowledged.

        If sec < 0 (the default), the operating system finishes sending the data in the background.

        If sec == 0, the operating system discards any unsent or unacknowledged data.

        If sec > 0, the data is sent in the background as with sec < 0. On some operating systems including Linux, this may cause Close to block until all data has been sent or discarded. On some operating systems after sec seconds have elapsed any remaining unsent data may be discarded.

        func (*TCPConn) SetNoDelay

        func (c *TCPConn) SetNoDelay(noDelay bool) error

        SetNoDelay controls whether the operating system should delay packet transmission in hopes of sending fewer packets (Nagle's algorithm). The default is true (no delay), meaning that data is sent as soon as possible after a Write.

        func (*TCPConn) SetReadBuffer

        func (c *TCPConn) SetReadBuffer(bytes int) error

        SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

        func (*TCPConn) SetReadDeadline

        func (c *TCPConn) SetReadDeadline(t time.Time) error

        SetReadDeadline implements the Conn SetReadDeadline method.

        func (*TCPConn) SetWriteBuffer

        func (c *TCPConn) SetWriteBuffer(bytes int) error

        SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

        func (*TCPConn) SetWriteDeadline

        func (c *TCPConn) SetWriteDeadline(t time.Time) error

        SetWriteDeadline implements the Conn SetWriteDeadline method.

        func (*TCPConn) SyscallConn

        func (c *TCPConn) SyscallConn() (syscall.RawConn, error)

        SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

        func (*TCPConn) Write

        func (c *TCPConn) Write(b []byte) (int, error)

        Write implements the Conn Write method.

        func (*TCPConn) WriteTo

        func (c *TCPConn) WriteTo(w io.Writer) (int64, error)

        WriteTo implements the io.WriterTo WriteTo method.

        type TCPListener

        TCPListener is a TCP network listener. Clients should typically use variables of type Listener instead of assuming TCP.

        type TCPListener struct {
            // contains filtered or unexported fields
        }
        

        func ListenTCP

        func ListenTCP(network string, laddr *TCPAddr) (*TCPListener, error)

        ListenTCP acts like Listen for TCP networks.

        The network must be a TCP network name; see func Dial for details.

        If the IP field of laddr is nil or an unspecified IP address, ListenTCP listens on all available unicast and anycast IP addresses of the local system. If the Port field of laddr is 0, a port number is automatically chosen.

        func (*TCPListener) Accept

        func (l *TCPListener) Accept() (Conn, error)

        Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn.

        func (*TCPListener) AcceptTCP

        func (l *TCPListener) AcceptTCP() (*TCPConn, error)

        AcceptTCP accepts the next incoming call and returns the new connection.

        func (*TCPListener) Addr

        func (l *TCPListener) Addr() Addr

        Addr returns the listener's network address, a *TCPAddr. The Addr returned is shared by all invocations of Addr, so do not modify it.

        func (*TCPListener) Close

        func (l *TCPListener) Close() error

        Close stops listening on the TCP address. Already Accepted connections are not closed.

        func (*TCPListener) File

        func (l *TCPListener) File() (f *os.File, err error)

        File returns a copy of the underlying os.File. It is the caller's responsibility to close f when finished. Closing l does not affect f, and closing f does not affect l.

        The returned os.File's file descriptor is different from the connection's. Attempting to change properties of the original using this duplicate may or may not have the desired effect.

        func (*TCPListener) SetDeadline

        func (l *TCPListener) SetDeadline(t time.Time) error

        SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.

        func (*TCPListener) SyscallConn

        func (l *TCPListener) SyscallConn() (syscall.RawConn, error)

        SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

        The returned RawConn only supports calling Control. Read and Write return an error.

        type UDPAddr

        UDPAddr represents the address of a UDP end point.

        type UDPAddr struct {
            IP   IP
            Port int
            Zone string // IPv6 scoped addressing zone
        }
        

        func ResolveUDPAddr

        func ResolveUDPAddr(network, address string) (*UDPAddr, error)

        ResolveUDPAddr returns an address of UDP end point.

        The network must be a UDP network name.

        If the host in the address parameter is not a literal IP address or the port is not a literal port number, ResolveUDPAddr resolves the address to an address of UDP end point. Otherwise, it parses the address as a pair of literal IP address and port number. The address parameter can use a host name, but this is not recommended, because it will return at most one of the host name's IP addresses.

        See func Dial for a description of the network and address parameters.

        func UDPAddrFromAddrPort

        func UDPAddrFromAddrPort(addr netip.AddrPort) *UDPAddr

        UDPAddrFromAddrPort returns addr as a UDPAddr. If addr.IsValid() is false, then the returned UDPAddr will contain a nil IP field, indicating an address family-agnostic unspecified address.

        func (*UDPAddr) AddrPort

        func (a *UDPAddr) AddrPort() netip.AddrPort

        AddrPort returns the UDPAddr a as a netip.AddrPort.

        If a.Port does not fit in a uint16, it's silently truncated.

        If a is nil, a zero value is returned.

        func (*UDPAddr) Network

        func (a *UDPAddr) Network() string

        Network returns the address's network name, "udp".

        func (*UDPAddr) String

        func (a *UDPAddr) String() string

        type UDPConn

        UDPConn is the implementation of the Conn and PacketConn interfaces for UDP network connections.

        type UDPConn struct {
            // contains filtered or unexported fields
        }
        

        func DialUDP

        func DialUDP(network string, laddr, raddr *UDPAddr) (*UDPConn, error)

        DialUDP acts like Dial for UDP networks.

        The network must be a UDP network name; see func Dial for details.

        If laddr is nil, a local address is automatically chosen. If the IP field of raddr is nil or an unspecified IP address, the local system is assumed.

        func ListenMulticastUDP

        func ListenMulticastUDP(network string, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error)

        ListenMulticastUDP acts like ListenPacket for UDP networks but takes a group address on a specific network interface.

        The network must be a UDP network name; see func Dial for details.

        ListenMulticastUDP listens on all available IP addresses of the local system including the group, multicast IP address. If ifi is nil, ListenMulticastUDP uses the system-assigned multicast interface, although this is not recommended because the assignment depends on platforms and sometimes it might require routing configuration. If the Port field of gaddr is 0, a port number is automatically chosen.

        ListenMulticastUDP is just for convenience of simple, small applications. There are golang.org/x/net/ipv4 and golang.org/x/net/ipv6 packages for general purpose uses.

        Note that ListenMulticastUDP will set the IP_MULTICAST_LOOP socket option to 0 under IPPROTO_IP, to disable loopback of multicast packets.

        func ListenUDP

        func ListenUDP(network string, laddr *UDPAddr) (*UDPConn, error)

        ListenUDP acts like ListenPacket for UDP networks.

        The network must be a UDP network name; see func Dial for details.

        If the IP field of laddr is nil or an unspecified IP address, ListenUDP listens on all available IP addresses of the local system except multicast IP addresses. If the Port field of laddr is 0, a port number is automatically chosen.

        func (*UDPConn) Close

        func (c *UDPConn) Close() error

        Close closes the connection.

        func (*UDPConn) File

        func (c *UDPConn) File() (f *os.File, err error)

        File returns a copy of the underlying os.File. It is the caller's responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.

        The returned os.File's file descriptor is different from the connection's. Attempting to change properties of the original using this duplicate may or may not have the desired effect.

        func (*UDPConn) LocalAddr

        func (c *UDPConn) LocalAddr() Addr

        LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.

        func (*UDPConn) Read

        func (c *UDPConn) Read(b []byte) (int, error)

        Read implements the Conn Read method.

        func (*UDPConn) ReadFrom

        func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error)

        ReadFrom implements the PacketConn ReadFrom method.

        func (*UDPConn) ReadFromUDP

        func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error)

        ReadFromUDP acts like ReadFrom but returns a UDPAddr.

        func (*UDPConn) ReadFromUDPAddrPort

        func (c *UDPConn) ReadFromUDPAddrPort(b []byte) (n int, addr netip.AddrPort, err error)

        ReadFromUDPAddrPort acts like ReadFrom but returns a netip.AddrPort.

        If c is bound to an unspecified address, the returned netip.AddrPort's address might be an IPv4-mapped IPv6 address. Use netip.Addr.Unmap to get the address without the IPv6 prefix.

        func (*UDPConn) ReadMsgUDP

        func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)

        ReadMsgUDP reads a message from c, copying the payload into b and the associated out-of-band data into oob. It returns the number of bytes copied into b, the number of bytes copied into oob, the flags that were set on the message and the source address of the message.

        The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

        func (*UDPConn) ReadMsgUDPAddrPort

        func (c *UDPConn) ReadMsgUDPAddrPort(b, oob []byte) (n, oobn, flags int, addr netip.AddrPort, err error)

        ReadMsgUDPAddrPort is like ReadMsgUDP but returns an netip.AddrPort instead of a UDPAddr.

        func (*UDPConn) RemoteAddr

        func (c *UDPConn) RemoteAddr() Addr

        RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.

        func (*UDPConn) SetDeadline

        func (c *UDPConn) SetDeadline(t time.Time) error

        SetDeadline implements the Conn SetDeadline method.

        func (*UDPConn) SetReadBuffer

        func (c *UDPConn) SetReadBuffer(bytes int) error

        SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

        func (*UDPConn) SetReadDeadline

        func (c *UDPConn) SetReadDeadline(t time.Time) error

        SetReadDeadline implements the Conn SetReadDeadline method.

        func (*UDPConn) SetWriteBuffer

        func (c *UDPConn) SetWriteBuffer(bytes int) error

        SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

        func (*UDPConn) SetWriteDeadline

        func (c *UDPConn) SetWriteDeadline(t time.Time) error

        SetWriteDeadline implements the Conn SetWriteDeadline method.

        func (*UDPConn) SyscallConn

        func (c *UDPConn) SyscallConn() (syscall.RawConn, error)

        SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

        func (*UDPConn) Write

        func (c *UDPConn) Write(b []byte) (int, error)

        Write implements the Conn Write method.

        func (*UDPConn) WriteMsgUDP

        func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobn int, err error)

        WriteMsgUDP writes a message to addr via c if c isn't connected, or to c's remote address if c is connected (in which case addr must be nil). The payload is copied from b and the associated out-of-band data is copied from oob. It returns the number of payload and out-of-band bytes written.

        The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

        func (*UDPConn) WriteMsgUDPAddrPort

        func (c *UDPConn) WriteMsgUDPAddrPort(b, oob []byte, addr netip.AddrPort) (n, oobn int, err error)

        WriteMsgUDPAddrPort is like WriteMsgUDP but takes a netip.AddrPort instead of a UDPAddr.

        func (*UDPConn) WriteTo

        func (c *UDPConn) WriteTo(b []byte, addr Addr) (int, error)

        WriteTo implements the PacketConn WriteTo method.

        Example

        Code:

        // Unlike Dial, ListenPacket creates a connection without any
        // association with peers.
        conn, err := net.ListenPacket("udp", ":0")
        if err != nil {
            log.Fatal(err)
        }
        defer conn.Close()
        
        dst, err := net.ResolveUDPAddr("udp", "192.0.2.1:2000")
        if err != nil {
            log.Fatal(err)
        }
        
        // The connection can write data to the desired address.
        _, err = conn.WriteTo([]byte("data"), dst)
        if err != nil {
            log.Fatal(err)
        }
        

        func (*UDPConn) WriteToUDP

        func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (int, error)

        WriteToUDP acts like WriteTo but takes a UDPAddr.

        func (*UDPConn) WriteToUDPAddrPort

        func (c *UDPConn) WriteToUDPAddrPort(b []byte, addr netip.AddrPort) (int, error)

        WriteToUDPAddrPort acts like WriteTo but takes a netip.AddrPort.

        type UnixAddr

        UnixAddr represents the address of a Unix domain socket end point.

        type UnixAddr struct {
            Name string
            Net  string
        }
        

        func ResolveUnixAddr

        func ResolveUnixAddr(network, address string) (*UnixAddr, error)

        ResolveUnixAddr returns an address of Unix domain socket end point.

        The network must be a Unix network name.

        See func Dial for a description of the network and address parameters.

        func (*UnixAddr) Network

        func (a *UnixAddr) Network() string

        Network returns the address's network name, "unix", "unixgram" or "unixpacket".

        func (*UnixAddr) String

        func (a *UnixAddr) String() string

        type UnixConn

        UnixConn is an implementation of the Conn interface for connections to Unix domain sockets.

        type UnixConn struct {
            // contains filtered or unexported fields
        }
        

        func DialUnix

        func DialUnix(network string, laddr, raddr *UnixAddr) (*UnixConn, error)

        DialUnix acts like Dial for Unix networks.

        The network must be a Unix network name; see func Dial for details.

        If laddr is non-nil, it is used as the local address for the connection.

        func ListenUnixgram

        func ListenUnixgram(network string, laddr *UnixAddr) (*UnixConn, error)

        ListenUnixgram acts like ListenPacket for Unix networks.

        The network must be "unixgram".

        func (*UnixConn) Close

        func (c *UnixConn) Close() error

        Close closes the connection.

        func (*UnixConn) CloseRead

        func (c *UnixConn) CloseRead() error

        CloseRead shuts down the reading side of the Unix domain connection. Most callers should just use Close.

        func (*UnixConn) CloseWrite

        func (c *UnixConn) CloseWrite() error

        CloseWrite shuts down the writing side of the Unix domain connection. Most callers should just use Close.

        func (*UnixConn) File

        func (c *UnixConn) File() (f *os.File, err error)

        File returns a copy of the underlying os.File. It is the caller's responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.

        The returned os.File's file descriptor is different from the connection's. Attempting to change properties of the original using this duplicate may or may not have the desired effect.

        func (*UnixConn) LocalAddr

        func (c *UnixConn) LocalAddr() Addr

        LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.

        func (*UnixConn) Read

        func (c *UnixConn) Read(b []byte) (int, error)

        Read implements the Conn Read method.

        func (*UnixConn) ReadFrom

        func (c *UnixConn) ReadFrom(b []byte) (int, Addr, error)

        ReadFrom implements the PacketConn ReadFrom method.

        func (*UnixConn) ReadFromUnix

        func (c *UnixConn) ReadFromUnix(b []byte) (int, *UnixAddr, error)

        ReadFromUnix acts like UnixConn.ReadFrom but returns a UnixAddr.

        func (*UnixConn) ReadMsgUnix

        func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error)

        ReadMsgUnix reads a message from c, copying the payload into b and the associated out-of-band data into oob. It returns the number of bytes copied into b, the number of bytes copied into oob, the flags that were set on the message and the source address of the message.

        Note that if len(b) == 0 and len(oob) > 0, this function will still read (and discard) 1 byte from the connection.

        func (*UnixConn) RemoteAddr

        func (c *UnixConn) RemoteAddr() Addr

        RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.

        func (*UnixConn) SetDeadline

        func (c *UnixConn) SetDeadline(t time.Time) error

        SetDeadline implements the Conn SetDeadline method.

        func (*UnixConn) SetReadBuffer

        func (c *UnixConn) SetReadBuffer(bytes int) error

        SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

        func (*UnixConn) SetReadDeadline

        func (c *UnixConn) SetReadDeadline(t time.Time) error

        SetReadDeadline implements the Conn SetReadDeadline method.

        func (*UnixConn) SetWriteBuffer

        func (c *UnixConn) SetWriteBuffer(bytes int) error

        SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

        func (*UnixConn) SetWriteDeadline

        func (c *UnixConn) SetWriteDeadline(t time.Time) error

        SetWriteDeadline implements the Conn SetWriteDeadline method.

        func (*UnixConn) SyscallConn

        func (c *UnixConn) SyscallConn() (syscall.RawConn, error)

        SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

        func (*UnixConn) Write

        func (c *UnixConn) Write(b []byte) (int, error)

        Write implements the Conn Write method.

        func (*UnixConn) WriteMsgUnix

        func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err error)

        WriteMsgUnix writes a message to addr via c, copying the payload from b and the associated out-of-band data from oob. It returns the number of payload and out-of-band bytes written.

        Note that if len(b) == 0 and len(oob) > 0, this function will still write 1 byte to the connection.

        func (*UnixConn) WriteTo

        func (c *UnixConn) WriteTo(b []byte, addr Addr) (int, error)

        WriteTo implements the PacketConn WriteTo method.

        func (*UnixConn) WriteToUnix

        func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (int, error)

        WriteToUnix acts like UnixConn.WriteTo but takes a UnixAddr.

        type UnixListener

        UnixListener is a Unix domain socket listener. Clients should typically use variables of type Listener instead of assuming Unix domain sockets.

        type UnixListener struct {
            // contains filtered or unexported fields
        }
        

        func ListenUnix

        func ListenUnix(network string, laddr *UnixAddr) (*UnixListener, error)

        ListenUnix acts like Listen for Unix networks.

        The network must be "unix" or "unixpacket".

        func (*UnixListener) Accept

        func (l *UnixListener) Accept() (Conn, error)

        Accept implements the Accept method in the Listener interface. Returned connections will be of type *UnixConn.

        func (*UnixListener) AcceptUnix

        func (l *UnixListener) AcceptUnix() (*UnixConn, error)

        AcceptUnix accepts the next incoming call and returns the new connection.

        func (*UnixListener) Addr

        func (l *UnixListener) Addr() Addr

        Addr returns the listener's network address. The Addr returned is shared by all invocations of Addr, so do not modify it.

        func (*UnixListener) Close

        func (l *UnixListener) Close() error

        Close stops listening on the Unix address. Already accepted connections are not closed.

        func (*UnixListener) File

        func (l *UnixListener) File() (f *os.File, err error)

        File returns a copy of the underlying os.File. It is the caller's responsibility to close f when finished. Closing l does not affect f, and closing f does not affect l.

        The returned os.File's file descriptor is different from the connection's. Attempting to change properties of the original using this duplicate may or may not have the desired effect.

        func (*UnixListener) SetDeadline

        func (l *UnixListener) SetDeadline(t time.Time) error

        SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.

        func (*UnixListener) SetUnlinkOnClose

        func (l *UnixListener) SetUnlinkOnClose(unlink bool)

        SetUnlinkOnClose sets whether the underlying socket file should be removed from the file system when the listener is closed.

        The default behavior is to unlink the socket file only when package net created it. That is, when the listener and the underlying socket file were created by a call to Listen or ListenUnix, then by default closing the listener will remove the socket file. but if the listener was created by a call to FileListener to use an already existing socket file, then by default closing the listener will not remove the socket file.

        func (*UnixListener) SyscallConn

        func (l *UnixListener) SyscallConn() (syscall.RawConn, error)

        SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

        The returned RawConn only supports calling Control. Read and Write return an error.

        type UnknownNetworkError

        type UnknownNetworkError string

        func (UnknownNetworkError) Error

        func (e UnknownNetworkError) Error() string

        func (UnknownNetworkError) Temporary

        func (e UnknownNetworkError) Temporary() bool

        func (UnknownNetworkError) Timeout

        func (e UnknownNetworkError) Timeout() bool

        Bugs

        • On JS and Windows, the FileConn, FileListener and FilePacketConn functions are not implemented.

        • On JS, methods and functions related to Interface are not implemented.

        • On AIX, DragonFly BSD, NetBSD, OpenBSD, Plan 9 and Solaris, the MulticastAddrs method of Interface is not implemented.

        • On every POSIX platform, reads from the "ip4" network using the ReadFrom or ReadFromIP method might not return a complete IPv4 packet, including its header, even if there is space available. This can occur even in cases where Read or ReadMsgIP could return a complete packet. For this reason, it is recommended that you do not use these methods if it is important to receive a full packet.

          The Go 1 compatibility guidelines make it impossible for us to change the behavior of these methods; use Read or ReadMsgIP instead.

        • On JS and Plan 9, methods and functions related to IPConn are not implemented.

        • On Windows, the File method of IPConn is not implemented.

        • On DragonFly BSD and OpenBSD, listening on the "tcp" and "udp" networks does not listen for both IPv4 and IPv6 connections. This is due to the fact that IPv4 traffic will not be routed to an IPv6 socket - two separate sockets are required if both address families are to be supported. See inet6(4) for details.

        • On Windows, the Write method of syscall.RawConn does not integrate with the runtime's network poller. It cannot wait for the connection to become writeable, and does not respect deadlines. If the user-provided callback returns false, the Write method will fail immediately.

        • On JS and Plan 9, the Control, Read and Write methods of syscall.RawConn are not implemented.

        • On JS and Windows, the File method of TCPConn and TCPListener is not implemented.

        • On Plan 9, the ReadMsgUDP and WriteMsgUDP methods of UDPConn are not implemented.

        • On Windows, the File method of UDPConn is not implemented.

        • On JS, methods and functions related to UDPConn are not implemented.

        • On JS, WASIP1 and Plan 9, methods and functions related to UnixConn and UnixListener are not implemented.

        • On Windows, methods and functions related to UnixConn and UnixListener don't work for "unixgram" and "unixpacket".

        Subdirectories

        Name Synopsis
        ..
        http Package http provides HTTP client and server implementations.
        cgi Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.
        cookiejar Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
        fcgi Package fcgi implements the FastCGI protocol.
        httptest Package httptest provides utilities for HTTP testing.
        httptrace Package httptrace provides mechanisms to trace the events within HTTP client requests.
        httputil Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package.
        pprof Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
        mail Package mail implements parsing of mail messages.
        netip Package netip defines an IP address type that's a small value type.
        rpc Package rpc provides access to the exported methods of an object across a network or other I/O connection.
        jsonrpc Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package.
        smtp Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
        textproto Package textproto implements generic support for text-based request/response protocols in the style of HTTP, NNTP, and SMTP.
        url Package url parses URLs and implements query escaping.
        http - Go Documentation Server
        ...

        Package http

        Overview ▾

        Package http provides HTTP client and server implementations.

        Get, Head, Post, and PostForm make HTTP (or HTTPS) requests:

        resp, err := http.Get("http://example.com/")
        ...
        resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
        ...
        resp, err := http.PostForm("http://example.com/form",
        	url.Values{"key": {"Value"}, "id": {"123"}})
        

        The caller must close the response body when finished with it:

        resp, err := http.Get("http://example.com/")
        if err != nil {
        	// handle error
        }
        defer resp.Body.Close()
        body, err := io.ReadAll(resp.Body)
        // ...
        

        Clients and Transports

        For control over HTTP client headers, redirect policy, and other settings, create a Client:

        client := &http.Client{
        	CheckRedirect: redirectPolicyFunc,
        }
        
        resp, err := client.Get("http://example.com")
        // ...
        
        req, err := http.NewRequest("GET", "http://example.com", nil)
        // ...
        req.Header.Add("If-None-Match", `W/"wyzzy"`)
        resp, err := client.Do(req)
        // ...
        

        For control over proxies, TLS configuration, keep-alives, compression, and other settings, create a Transport:

        tr := &http.Transport{
        	MaxIdleConns:       10,
        	IdleConnTimeout:    30 * time.Second,
        	DisableCompression: true,
        }
        client := &http.Client{Transport: tr}
        resp, err := client.Get("https://example.com")
        

        Clients and Transports are safe for concurrent use by multiple goroutines and for efficiency should only be created once and re-used.

        Servers

        ListenAndServe starts an HTTP server with a given address and handler. The handler is usually nil, which means to use DefaultServeMux. Handle and HandleFunc add handlers to DefaultServeMux:

        http.Handle("/foo", fooHandler)
        
        http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
        	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
        })
        
        log.Fatal(http.ListenAndServe(":8080", nil))
        

        More control over the server's behavior is available by creating a custom Server:

        s := &http.Server{
        	Addr:           ":8080",
        	Handler:        myHandler,
        	ReadTimeout:    10 * time.Second,
        	WriteTimeout:   10 * time.Second,
        	MaxHeaderBytes: 1 << 20,
        }
        log.Fatal(s.ListenAndServe())
        

        HTTP/2

        Starting with Go 1.6, the http package has transparent support for the HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 can do so by setting [Transport.TLSNextProto] (for clients) or [Server.TLSNextProto] (for servers) to a non-nil, empty map. Alternatively, the following GODEBUG settings are currently supported:

        GODEBUG=http2client=0  # disable HTTP/2 client support
        GODEBUG=http2server=0  # disable HTTP/2 server support
        GODEBUG=http2debug=1   # enable verbose HTTP/2 debug logs
        GODEBUG=http2debug=2   # ... even more verbose, with frame dumps
        

        Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug

        The http package's Transport and Server both automatically enable HTTP/2 support for simple configurations. To enable HTTP/2 for more complex configurations, to use lower-level HTTP/2 features, or to use a newer version of Go's http2 package, import "golang.org/x/net/http2" directly and use its ConfigureTransport and/or ConfigureServer functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 package takes precedence over the net/http package's built-in HTTP/2 support.

        Index ▾

        Constants
        Variables
        func CanonicalHeaderKey(s string) string
        func DetectContentType(data []byte) string
        func Error(w ResponseWriter, error string, code int)
        func Handle(pattern string, handler Handler)
        func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
        func ListenAndServe(addr string, handler Handler) error
        func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
        func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
        func NotFound(w ResponseWriter, r *Request)
        func ParseHTTPVersion(vers string) (major, minor int, ok bool)
        func ParseTime(text string) (t time.Time, err error)
        func ProxyFromEnvironment(req *Request) (*url.URL, error)
        func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)
        func Redirect(w ResponseWriter, r *Request, url string, code int)
        func Serve(l net.Listener, handler Handler) error
        func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
        func ServeFile(w ResponseWriter, r *Request, name string)
        func ServeFileFS(w ResponseWriter, r *Request, fsys fs.FS, name string)
        func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error
        func SetCookie(w ResponseWriter, cookie *Cookie)
        func StatusText(code int) string
        type Client
            func (c *Client) CloseIdleConnections()
            func (c *Client) Do(req *Request) (*Response, error)
            func (c *Client) Get(url string) (resp *Response, err error)
            func (c *Client) Head(url string) (resp *Response, err error)
            func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)
            func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
        type CloseNotifier
        type ConnState
            func (c ConnState) String() string
        type Cookie
            func (c *Cookie) String() string
            func (c *Cookie) Valid() error
        type CookieJar
        type Dir
            func (d Dir) Open(name string) (File, error)
        type File
        type FileSystem
            func FS(fsys fs.FS) FileSystem
        type Flusher
        type Handler
            func AllowQuerySemicolons(h Handler) Handler
            func FileServer(root FileSystem) Handler
            func FileServerFS(root fs.FS) Handler
            func MaxBytesHandler(h Handler, n int64) Handler
            func NotFoundHandler() Handler
            func RedirectHandler(url string, code int) Handler
            func StripPrefix(prefix string, h Handler) Handler
            func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler
        type HandlerFunc
            func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)
        type Header
            func (h Header) Add(key, value string)
            func (h Header) Clone() Header
            func (h Header) Del(key string)
            func (h Header) Get(key string) string
            func (h Header) Set(key, value string)
            func (h Header) Values(key string) []string
            func (h Header) Write(w io.Writer) error
            func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error
        type Hijacker
        type MaxBytesError
            func (e *MaxBytesError) Error() string
        type ProtocolError
            func (pe *ProtocolError) Error() string
            func (pe *ProtocolError) Is(err error) bool
        type PushOptions
        type Pusher
        type Request
            func NewRequest(method, url string, body io.Reader) (*Request, error)
            func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
            func ReadRequest(b *bufio.Reader) (*Request, error)
            func (r *Request) AddCookie(c *Cookie)
            func (r *Request) BasicAuth() (username, password string, ok bool)
            func (r *Request) Clone(ctx context.Context) *Request
            func (r *Request) Context() context.Context
            func (r *Request) Cookie(name string) (*Cookie, error)
            func (r *Request) Cookies() []*Cookie
            func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
            func (r *Request) FormValue(key string) string
            func (r *Request) MultipartReader() (*multipart.Reader, error)
            func (r *Request) ParseForm() error
            func (r *Request) ParseMultipartForm(maxMemory int64) error
            func (r *Request) PathValue(name string) string
            func (r *Request) PostFormValue(key string) string
            func (r *Request) ProtoAtLeast(major, minor int) bool
            func (r *Request) Referer() string
            func (r *Request) SetBasicAuth(username, password string)
            func (r *Request) SetPathValue(name, value string)
            func (r *Request) UserAgent() string
            func (r *Request) WithContext(ctx context.Context) *Request
            func (r *Request) Write(w io.Writer) error
            func (r *Request) WriteProxy(w io.Writer) error
        type Response
            func Get(url string) (resp *Response, err error)
            func Head(url string) (resp *Response, err error)
            func Post(url, contentType string, body io.Reader) (resp *Response, err error)
            func PostForm(url string, data url.Values) (resp *Response, err error)
            func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
            func (r *Response) Cookies() []*Cookie
            func (r *Response) Location() (*url.URL, error)
            func (r *Response) ProtoAtLeast(major, minor int) bool
            func (r *Response) Write(w io.Writer) error
        type ResponseController
            func NewResponseController(rw ResponseWriter) *ResponseController
            func (c *ResponseController) EnableFullDuplex() error
            func (c *ResponseController) Flush() error
            func (c *ResponseController) Hijack() (net.Conn, *bufio.ReadWriter, error)
            func (c *ResponseController) SetReadDeadline(deadline time.Time) error
            func (c *ResponseController) SetWriteDeadline(deadline time.Time) error
        type ResponseWriter
        type RoundTripper
            func NewFileTransport(fs FileSystem) RoundTripper
            func NewFileTransportFS(fsys fs.FS) RoundTripper
        type SameSite
        type ServeMux
            func NewServeMux() *ServeMux
            func (mux *ServeMux) Handle(pattern string, handler Handler)
            func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
            func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)
            func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
        type Server
            func (srv *Server) Close() error
            func (srv *Server) ListenAndServe() error
            func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error
            func (srv *Server) RegisterOnShutdown(f func())
            func (srv *Server) Serve(l net.Listener) error
            func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error
            func (srv *Server) SetKeepAlivesEnabled(v bool)
            func (srv *Server) Shutdown(ctx context.Context) error
        type Transport
            func (t *Transport) CancelRequest(req *Request)
            func (t *Transport) Clone() *Transport
            func (t *Transport) CloseIdleConnections()
            func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)
            func (t *Transport) RoundTrip(req *Request) (*Response, error)

        Package files

        client.go clone.go cookie.go doc.go filetransport.go fs.go h2_bundle.go h2_error.go header.go http.go jar.go mapping.go method.go pattern.go request.go response.go responsecontroller.go roundtrip.go routing_index.go routing_tree.go servemux121.go server.go sniff.go socks_bundle.go status.go transfer.go transport.go transport_default_other.go

        Constants

        Common HTTP methods.

        Unless otherwise noted, these are defined in RFC 7231 section 4.3.

        const (
            MethodGet     = "GET"
            MethodHead    = "HEAD"
            MethodPost    = "POST"
            MethodPut     = "PUT"
            MethodPatch   = "PATCH" // RFC 5789
            MethodDelete  = "DELETE"
            MethodConnect = "CONNECT"
            MethodOptions = "OPTIONS"
            MethodTrace   = "TRACE"
        )

        HTTP status codes as registered with IANA. See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

        const (
            StatusContinue           = 100 // RFC 9110, 15.2.1
            StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2
            StatusProcessing         = 102 // RFC 2518, 10.1
            StatusEarlyHints         = 103 // RFC 8297
        
            StatusOK                   = 200 // RFC 9110, 15.3.1
            StatusCreated              = 201 // RFC 9110, 15.3.2
            StatusAccepted             = 202 // RFC 9110, 15.3.3
            StatusNonAuthoritativeInfo = 203 // RFC 9110, 15.3.4
            StatusNoContent            = 204 // RFC 9110, 15.3.5
            StatusResetContent         = 205 // RFC 9110, 15.3.6
            StatusPartialContent       = 206 // RFC 9110, 15.3.7
            StatusMultiStatus          = 207 // RFC 4918, 11.1
            StatusAlreadyReported      = 208 // RFC 5842, 7.1
            StatusIMUsed               = 226 // RFC 3229, 10.4.1
        
            StatusMultipleChoices  = 300 // RFC 9110, 15.4.1
            StatusMovedPermanently = 301 // RFC 9110, 15.4.2
            StatusFound            = 302 // RFC 9110, 15.4.3
            StatusSeeOther         = 303 // RFC 9110, 15.4.4
            StatusNotModified      = 304 // RFC 9110, 15.4.5
            StatusUseProxy         = 305 // RFC 9110, 15.4.6
        
            StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8
            StatusPermanentRedirect = 308 // RFC 9110, 15.4.9
        
            StatusBadRequest                   = 400 // RFC 9110, 15.5.1
            StatusUnauthorized                 = 401 // RFC 9110, 15.5.2
            StatusPaymentRequired              = 402 // RFC 9110, 15.5.3
            StatusForbidden                    = 403 // RFC 9110, 15.5.4
            StatusNotFound                     = 404 // RFC 9110, 15.5.5
            StatusMethodNotAllowed             = 405 // RFC 9110, 15.5.6
            StatusNotAcceptable                = 406 // RFC 9110, 15.5.7
            StatusProxyAuthRequired            = 407 // RFC 9110, 15.5.8
            StatusRequestTimeout               = 408 // RFC 9110, 15.5.9
            StatusConflict                     = 409 // RFC 9110, 15.5.10
            StatusGone                         = 410 // RFC 9110, 15.5.11
            StatusLengthRequired               = 411 // RFC 9110, 15.5.12
            StatusPreconditionFailed           = 412 // RFC 9110, 15.5.13
            StatusRequestEntityTooLarge        = 413 // RFC 9110, 15.5.14
            StatusRequestURITooLong            = 414 // RFC 9110, 15.5.15
            StatusUnsupportedMediaType         = 415 // RFC 9110, 15.5.16
            StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17
            StatusExpectationFailed            = 417 // RFC 9110, 15.5.18
            StatusTeapot                       = 418 // RFC 9110, 15.5.19 (Unused)
            StatusMisdirectedRequest           = 421 // RFC 9110, 15.5.20
            StatusUnprocessableEntity          = 422 // RFC 9110, 15.5.21
            StatusLocked                       = 423 // RFC 4918, 11.3
            StatusFailedDependency             = 424 // RFC 4918, 11.4
            StatusTooEarly                     = 425 // RFC 8470, 5.2.
            StatusUpgradeRequired              = 426 // RFC 9110, 15.5.22
            StatusPreconditionRequired         = 428 // RFC 6585, 3
            StatusTooManyRequests              = 429 // RFC 6585, 4
            StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
            StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3
        
            StatusInternalServerError           = 500 // RFC 9110, 15.6.1
            StatusNotImplemented                = 501 // RFC 9110, 15.6.2
            StatusBadGateway                    = 502 // RFC 9110, 15.6.3
            StatusServiceUnavailable            = 503 // RFC 9110, 15.6.4
            StatusGatewayTimeout                = 504 // RFC 9110, 15.6.5
            StatusHTTPVersionNotSupported       = 505 // RFC 9110, 15.6.6
            StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
            StatusInsufficientStorage           = 507 // RFC 4918, 11.5
            StatusLoopDetected                  = 508 // RFC 5842, 7.2
            StatusNotExtended                   = 510 // RFC 2774, 7
            StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
        )

        DefaultMaxHeaderBytes is the maximum permitted size of the headers in an HTTP request. This can be overridden by setting [Server.MaxHeaderBytes].

        const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
        

        DefaultMaxIdleConnsPerHost is the default value of Transport's MaxIdleConnsPerHost.

        const DefaultMaxIdleConnsPerHost = 2

        TimeFormat is the time format to use when generating times in HTTP headers. It is like time.RFC1123 but hard-codes GMT as the time zone. The time being formatted must be in UTC for Format to generate the correct format.

        For parsing this time format, see ParseTime.

        const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

        TrailerPrefix is a magic prefix for [ResponseWriter.Header] map keys that, if present, signals that the map entry is actually for the response trailers, and not the response headers. The prefix is stripped after the ServeHTTP call finishes and the values are sent in the trailers.

        This mechanism is intended only for trailers that are not known prior to the headers being written. If the set of trailers is fixed or known before the header is written, the normal Go trailers mechanism is preferred:

        https://pkg.go.dev/net/http#ResponseWriter
        https://pkg.go.dev/net/http#example-ResponseWriter-Trailers
        
        const TrailerPrefix = "Trailer:"

        Variables

        var (
            // ErrNotSupported indicates that a feature is not supported.
            //
            // It is returned by ResponseController methods to indicate that
            // the handler does not support the method, and by the Push method
            // of Pusher implementations to indicate that HTTP/2 Push support
            // is not available.
            ErrNotSupported = &ProtocolError{"feature not supported"}
        
            // Deprecated: ErrUnexpectedTrailer is no longer returned by
            // anything in the net/http package. Callers should not
            // compare errors against this variable.
            ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"}
        
            // ErrMissingBoundary is returned by Request.MultipartReader when the
            // request's Content-Type does not include a "boundary" parameter.
            ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"}
        
            // ErrNotMultipart is returned by Request.MultipartReader when the
            // request's Content-Type is not multipart/form-data.
            ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"}
        
            // Deprecated: ErrHeaderTooLong is no longer returned by
            // anything in the net/http package. Callers should not
            // compare errors against this variable.
            ErrHeaderTooLong = &ProtocolError{"header too long"}
        
            // Deprecated: ErrShortBody is no longer returned by
            // anything in the net/http package. Callers should not
            // compare errors against this variable.
            ErrShortBody = &ProtocolError{"entity body too short"}
        
            // Deprecated: ErrMissingContentLength is no longer returned by
            // anything in the net/http package. Callers should not
            // compare errors against this variable.
            ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"}
        )

        Errors used by the HTTP server.

        var (
            // ErrBodyNotAllowed is returned by ResponseWriter.Write calls
            // when the HTTP method or response code does not permit a
            // body.
            ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
        
            // ErrHijacked is returned by ResponseWriter.Write calls when
            // the underlying connection has been hijacked using the
            // Hijacker interface. A zero-byte write on a hijacked
            // connection will return ErrHijacked without any other side
            // effects.
            ErrHijacked = errors.New("http: connection has been hijacked")
        
            // ErrContentLength is returned by ResponseWriter.Write calls
            // when a Handler set a Content-Length response header with a
            // declared size and then attempted to write more bytes than
            // declared.
            ErrContentLength = errors.New("http: wrote more than the declared Content-Length")
        
            // Deprecated: ErrWriteAfterFlush is no longer returned by
            // anything in the net/http package. Callers should not
            // compare errors against this variable.
            ErrWriteAfterFlush = errors.New("unused")
        )
        var (
            // ServerContextKey is a context key. It can be used in HTTP
            // handlers with Context.Value to access the server that
            // started the handler. The associated value will be of
            // type *Server.
            ServerContextKey = &contextKey{"http-server"}
        
            // LocalAddrContextKey is a context key. It can be used in
            // HTTP handlers with Context.Value to access the local
            // address the connection arrived on.
            // The associated value will be of type net.Addr.
            LocalAddrContextKey = &contextKey{"local-addr"}
        )

        DefaultClient is the default Client and is used by Get, Head, and Post.

        var DefaultClient = &Client{}

        DefaultServeMux is the default ServeMux used by Serve.

        var DefaultServeMux = &defaultServeMux

        ErrAbortHandler is a sentinel panic value to abort a handler. While any panic from ServeHTTP aborts the response to the client, panicking with ErrAbortHandler also suppresses logging of a stack trace to the server's error log.

        var ErrAbortHandler = errors.New("net/http: abort Handler")

        ErrBodyReadAfterClose is returned when reading a Request or Response Body after the body has been closed. This typically happens when the body is read after an HTTP Handler calls WriteHeader or Write on its ResponseWriter.

        var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")

        ErrHandlerTimeout is returned on ResponseWriter Write calls in handlers which have timed out.

        var ErrHandlerTimeout = errors.New("http: Handler timeout")

        ErrLineTooLong is returned when reading request or response bodies with malformed chunked encoding.

        var ErrLineTooLong = internal.ErrLineTooLong

        ErrMissingFile is returned by FormFile when the provided file field name is either not present in the request or not a file field.

        var ErrMissingFile = errors.New("http: no such file")

        ErrNoCookie is returned by Request's Cookie method when a cookie is not found.

        var ErrNoCookie = errors.New("http: named cookie not present")

        ErrNoLocation is returned by the Response.Location method when no Location header is present.

        var ErrNoLocation = errors.New("http: no Location header in response")

        ErrSchemeMismatch is returned when a server returns an HTTP response to an HTTPS client.

        var ErrSchemeMismatch = errors.New("http: server gave HTTP response to HTTPS client")

        ErrServerClosed is returned by the Server.Serve, ServeTLS, ListenAndServe, and ListenAndServeTLS methods after a call to Server.Shutdown or Server.Close.

        var ErrServerClosed = errors.New("http: Server closed")

        ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol.

        var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")

        ErrUseLastResponse can be returned by Client.CheckRedirect hooks to control how redirects are processed. If returned, the next request is not sent and the most recent response is returned with its body unclosed.

        var ErrUseLastResponse = errors.New("net/http: use last response")

        NoBody is an io.ReadCloser with no bytes. Read always returns EOF and Close always returns nil. It can be used in an outgoing client request to explicitly signal that a request has zero bytes. An alternative, however, is to simply set [Request.Body] to nil.

        var NoBody = noBody{}

        func CanonicalHeaderKey

        func CanonicalHeaderKey(s string) string

        CanonicalHeaderKey returns the canonical format of the header key s. The canonicalization converts the first letter and any letter following a hyphen to upper case; the rest are converted to lowercase. For example, the canonical key for "accept-encoding" is "Accept-Encoding". If s contains a space or invalid header field bytes, it is returned without modifications.

        func DetectContentType

        func DetectContentType(data []byte) string

        DetectContentType implements the algorithm described at https://mimesniff.spec.whatwg.org/ to determine the Content-Type of the given data. It considers at most the first 512 bytes of data. DetectContentType always returns a valid MIME type: if it cannot determine a more specific one, it returns "application/octet-stream".

        func Error

        func Error(w ResponseWriter, error string, code int)

        Error replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be plain text.

        func Handle

        func Handle(pattern string, handler Handler)

        Handle registers the handler for the given pattern in DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

        Example

        Code:

        package http_test
        
        import (
            "fmt"
            "log"
            "net/http"
            "sync"
        )
        
        type countHandler struct {
            mu sync.Mutex // guards n
            n  int
        }
        
        func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
            h.mu.Lock()
            defer h.mu.Unlock()
            h.n++
            fmt.Fprintf(w, "count is %d\n", h.n)
        }
        
        func ExampleHandle() {
            http.Handle("/count", new(countHandler))
            log.Fatal(http.ListenAndServe(":8080", nil))
        }
        

        func HandleFunc

        func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

        HandleFunc registers the handler function for the given pattern in DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

        Example

        Code:

        h1 := func(w http.ResponseWriter, _ *http.Request) {
            io.WriteString(w, "Hello from a HandleFunc #1!\n")
        }
        h2 := func(w http.ResponseWriter, _ *http.Request) {
            io.WriteString(w, "Hello from a HandleFunc #2!\n")
        }
        
        http.HandleFunc("/", h1)
        http.HandleFunc("/endpoint", h2)
        
        log.Fatal(http.ListenAndServe(":8080", nil))
        

        func ListenAndServe

        func ListenAndServe(addr string, handler Handler) error

        ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.

        The handler is typically nil, in which case DefaultServeMux is used.

        ListenAndServe always returns a non-nil error.

        Example

        Code:

        // Hello world, the web server
        
        helloHandler := func(w http.ResponseWriter, req *http.Request) {
            io.WriteString(w, "Hello, world!\n")
        }
        
        http.HandleFunc("/hello", helloHandler)
        log.Fatal(http.ListenAndServe(":8080", nil))
        

        func ListenAndServeTLS

        func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error

        ListenAndServeTLS acts identically to ListenAndServe, except that it expects HTTPS connections. Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

        Example

        Code:

        http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
            io.WriteString(w, "Hello, TLS!\n")
        })
        
        // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
        log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/")
        err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
        log.Fatal(err)
        

        func MaxBytesReader

        func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser

        MaxBytesReader is similar to io.LimitReader but is intended for limiting the size of incoming request bodies. In contrast to io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a non-nil error of type *MaxBytesError for a Read beyond the limit, and closes the underlying reader when its Close method is called.

        MaxBytesReader prevents clients from accidentally or maliciously sending a large request and wasting server resources. If possible, it tells the ResponseWriter to close the connection after the limit has been reached.

        func NotFound

        func NotFound(w ResponseWriter, r *Request)

        NotFound replies to the request with an HTTP 404 not found error.

        func ParseHTTPVersion

        func ParseHTTPVersion(vers string) (major, minor int, ok bool)

        ParseHTTPVersion parses an HTTP version string according to RFC 7230, section 2.6. "HTTP/1.0" returns (1, 0, true). Note that strings without a minor version, such as "HTTP/2", are not valid.

        func ParseTime

        func ParseTime(text string) (t time.Time, err error)

        ParseTime parses a time header (such as the Date: header), trying each of the three formats allowed by HTTP/1.1: TimeFormat, time.RFC850, and time.ANSIC.

        func ProxyFromEnvironment

        func ProxyFromEnvironment(req *Request) (*url.URL, error)

        ProxyFromEnvironment returns the URL of the proxy to use for a given request, as indicated by the environment variables HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions thereof). Requests use the proxy from the environment variable matching their scheme, unless excluded by NO_PROXY.

        The environment values may be either a complete URL or a "host[:port]", in which case the "http" scheme is assumed. The schemes "http", "https", and "socks5" are supported. An error is returned if the value is a different form.

        A nil URL and nil error are returned if no proxy is defined in the environment, or a proxy should not be used for the given request, as defined by NO_PROXY.

        As a special case, if req.URL.Host is "localhost" (with or without a port number), then a nil URL and nil error will be returned.

        func ProxyURL

        func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)

        ProxyURL returns a proxy function (for use in a Transport) that always returns the same URL.

        func Redirect

        func Redirect(w ResponseWriter, r *Request, url string, code int)

        Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

        The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.

        If the Content-Type header has not been set, Redirect sets it to "text/html; charset=utf-8" and writes a small HTML body. Setting the Content-Type header to any value, including nil, disables that behavior.

        func Serve

        func Serve(l net.Listener, handler Handler) error

        Serve accepts incoming HTTP connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.

        The handler is typically nil, in which case DefaultServeMux is used.

        HTTP/2 support is only enabled if the Listener returns *tls.Conn connections and they were configured with "h2" in the TLS Config.NextProtos.

        Serve always returns a non-nil error.

        func ServeContent

        func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)

        ServeContent replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests.

        If the response's Content-Type header is not set, ServeContent first tries to deduce the type from name's file extension and, if that fails, falls back to reading the first block of the content and passing it to DetectContentType. The name is otherwise unused; in particular it can be empty and is never sent in the response.

        If modtime is not the zero time or Unix epoch, ServeContent includes it in a Last-Modified header in the response. If the request includes an If-Modified-Since header, ServeContent uses modtime to decide whether the content needs to be sent at all.

        The content's Seek method must work: ServeContent uses a seek to the end of the content to determine its size.

        If the caller has set w's ETag header formatted per RFC 7232, section 2.3, ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.

        Note that *os.File implements the io.ReadSeeker interface.

        func ServeFile

        func ServeFile(w ResponseWriter, r *Request, name string)

        ServeFile replies to the request with the contents of the named file or directory.

        If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories. If the provided name is constructed from user input, it should be sanitized before calling ServeFile.

        As a precaution, ServeFile will reject requests where r.URL.Path contains a ".." path element; this protects against callers who might unsafely use filepath.Join on r.URL.Path without sanitizing it and then use that filepath.Join result as the name argument.

        As another special case, ServeFile redirects any request where r.URL.Path ends in "/index.html" to the same path, without the final "index.html". To avoid such redirects either modify the path or use ServeContent.

        Outside of those two special cases, ServeFile does not use r.URL.Path for selecting the file or directory to serve; only the file or directory provided in the name argument is used.

        func ServeFileFS

        func ServeFileFS(w ResponseWriter, r *Request, fsys fs.FS, name string)

        ServeFileFS replies to the request with the contents of the named file or directory from the file system fsys.

        If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories. If the provided name is constructed from user input, it should be sanitized before calling ServeFile.

        As a precaution, ServeFile will reject requests where r.URL.Path contains a ".." path element; this protects against callers who might unsafely use filepath.Join on r.URL.Path without sanitizing it and then use that filepath.Join result as the name argument.

        As another special case, ServeFile redirects any request where r.URL.Path ends in "/index.html" to the same path, without the final "index.html". To avoid such redirects either modify the path or use ServeContent.

        Outside of those two special cases, ServeFile does not use r.URL.Path for selecting the file or directory to serve; only the file or directory provided in the name argument is used.

        func ServeTLS

        func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error

        ServeTLS accepts incoming HTTPS connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.

        The handler is typically nil, in which case DefaultServeMux is used.

        Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

        ServeTLS always returns a non-nil error.

        func SetCookie

        func SetCookie(w ResponseWriter, cookie *Cookie)

        SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

        func StatusText

        func StatusText(code int) string

        StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

        type Client

        A Client is an HTTP client. Its zero value (DefaultClient) is a usable client that uses DefaultTransport.

        The [Client.Transport] typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.

        A Client is higher-level than a RoundTripper (such as Transport) and additionally handles HTTP details such as cookies and redirects.

        When following redirects, the Client will forward all headers set on the initial Request except:

        • when forwarding sensitive headers like "Authorization", "WWW-Authenticate", and "Cookie" to untrusted targets. These headers will be ignored when following a redirect to a domain that is not a subdomain match or exact match of the initial domain. For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" will forward the sensitive headers, but a redirect to "bar.com" will not.
        • when forwarding the "Cookie" header with a non-nil cookie Jar. Since each redirect may mutate the state of the cookie jar, a redirect may possibly alter a cookie set in the initial request. When forwarding the "Cookie" header, any mutated cookies will be omitted, with the expectation that the Jar will insert those mutated cookies with the updated values (assuming the origin matches). If Jar is nil, the initial cookies are forwarded without change.
        type Client struct {
            // Transport specifies the mechanism by which individual
            // HTTP requests are made.
            // If nil, DefaultTransport is used.
            Transport RoundTripper
        
            // CheckRedirect specifies the policy for handling redirects.
            // If CheckRedirect is not nil, the client calls it before
            // following an HTTP redirect. The arguments req and via are
            // the upcoming request and the requests made already, oldest
            // first. If CheckRedirect returns an error, the Client's Get
            // method returns both the previous Response (with its Body
            // closed) and CheckRedirect's error (wrapped in a url.Error)
            // instead of issuing the Request req.
            // As a special case, if CheckRedirect returns ErrUseLastResponse,
            // then the most recent response is returned with its body
            // unclosed, along with a nil error.
            //
            // If CheckRedirect is nil, the Client uses its default policy,
            // which is to stop after 10 consecutive requests.
            CheckRedirect func(req *Request, via []*Request) error
        
            // Jar specifies the cookie jar.
            //
            // The Jar is used to insert relevant cookies into every
            // outbound Request and is updated with the cookie values
            // of every inbound Response. The Jar is consulted for every
            // redirect that the Client follows.
            //
            // If Jar is nil, cookies are only sent if they are explicitly
            // set on the Request.
            Jar CookieJar
        
            // Timeout specifies a time limit for requests made by this
            // Client. The timeout includes connection time, any
            // redirects, and reading the response body. The timer remains
            // running after Get, Head, Post, or Do return and will
            // interrupt reading of the Response.Body.
            //
            // A Timeout of zero means no timeout.
            //
            // The Client cancels requests to the underlying Transport
            // as if the Request's Context ended.
            //
            // For compatibility, the Client will also use the deprecated
            // CancelRequest method on Transport if found. New
            // RoundTripper implementations should use the Request's Context
            // for cancellation instead of implementing CancelRequest.
            Timeout time.Duration
        }
        

        func (*Client) CloseIdleConnections

        func (c *Client) CloseIdleConnections()

        CloseIdleConnections closes any connections on its Transport which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.

        If [Client.Transport] does not have a Client.CloseIdleConnections method then this method does nothing.

        func (*Client) Do

        func (c *Client) Do(req *Request) (*Response, error)

        Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.

        An error is returned if caused by client policy (such as CheckRedirect), or failure to speak HTTP (such as a network connectivity problem). A non-2xx status code doesn't cause an error.

        If the returned error is nil, the Response will contain a non-nil Body which the user is expected to close. If the Body is not both read to EOF and closed, the Client's underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection to the server for a subsequent "keep-alive" request.

        The request Body, if non-nil, will be closed by the underlying Transport, even on errors. The Body may be closed asynchronously after Do returns.

        On error, any Response can be ignored. A non-nil Response with a non-nil error only occurs when CheckRedirect fails, and even then the returned [Response.Body] is already closed.

        Generally Get, Post, or PostForm will be used instead of Do.

        If the server replies with a redirect, the Client first uses the CheckRedirect function to determine whether the redirect should be followed. If permitted, a 301, 302, or 303 redirect causes subsequent requests to use HTTP method GET (or HEAD if the original request was HEAD), with no body. A 307 or 308 redirect preserves the original HTTP method and body, provided that the [Request.GetBody] function is defined. The NewRequest function automatically sets GetBody for common standard library body types.

        Any returned error will be of type *url.Error. The url.Error value's Timeout method will report true if the request timed out.

        func (*Client) Get

        func (c *Client) Get(url string) (resp *Response, err error)

        Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect after calling the [Client.CheckRedirect] function:

        301 (Moved Permanently)
        302 (Found)
        303 (See Other)
        307 (Temporary Redirect)
        308 (Permanent Redirect)
        

        An error is returned if the [Client.CheckRedirect] function fails or if there was an HTTP protocol error. A non-2xx response doesn't cause an error. Any returned error will be of type *url.Error. The url.Error value's Timeout method will report true if the request timed out.

        When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.

        To make a request with custom headers, use NewRequest and Client.Do.

        To make a request with a specified context.Context, use NewRequestWithContext and Client.Do.

        func (*Client) Head

        func (c *Client) Head(url string) (resp *Response, err error)

        Head issues a HEAD to the specified URL. If the response is one of the following redirect codes, Head follows the redirect after calling the [Client.CheckRedirect] function:

        301 (Moved Permanently)
        302 (Found)
        303 (See Other)
        307 (Temporary Redirect)
        308 (Permanent Redirect)
        

        To make a request with a specified context.Context, use NewRequestWithContext and Client.Do.

        func (*Client) Post

        func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)

        Post issues a POST to the specified URL.

        Caller should close resp.Body when done reading from it.

        If the provided body is an io.Closer, it is closed after the request.

        To set custom headers, use NewRequest and Client.Do.

        To make a request with a specified context.Context, use NewRequestWithContext and Client.Do.

        See the Client.Do method documentation for details on how redirects are handled.

        func (*Client) PostForm

        func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)

        PostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body.

        The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use NewRequest and Client.Do.

        When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.

        See the Client.Do method documentation for details on how redirects are handled.

        To make a request with a specified context.Context, use NewRequestWithContext and Client.Do.

        type CloseNotifier

        The CloseNotifier interface is implemented by ResponseWriters which allow detecting when the underlying connection has gone away.

        This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready.

        Deprecated: the CloseNotifier interface predates Go's context package. New code should use Request.Context instead.

        type CloseNotifier interface {
            // CloseNotify returns a channel that receives at most a
            // single value (true) when the client connection has gone
            // away.
            //
            // CloseNotify may wait to notify until Request.Body has been
            // fully read.
            //
            // After the Handler has returned, there is no guarantee
            // that the channel receives a value.
            //
            // If the protocol is HTTP/1.1 and CloseNotify is called while
            // processing an idempotent request (such a GET) while
            // HTTP/1.1 pipelining is in use, the arrival of a subsequent
            // pipelined request may cause a value to be sent on the
            // returned channel. In practice HTTP/1.1 pipelining is not
            // enabled in browsers and not seen often in the wild. If this
            // is a problem, use HTTP/2 or only use CloseNotify on methods
            // such as POST.
            CloseNotify() <-chan bool
        }

        type ConnState

        A ConnState represents the state of a client connection to a server. It's used by the optional [Server.ConnState] hook.

        type ConnState int
        const (
            // StateNew represents a new connection that is expected to
            // send a request immediately. Connections begin at this
            // state and then transition to either StateActive or
            // StateClosed.
            StateNew ConnState = iota
        
            // StateActive represents a connection that has read 1 or more
            // bytes of a request. The Server.ConnState hook for
            // StateActive fires before the request has entered a handler
            // and doesn't fire again until the request has been
            // handled. After the request is handled, the state
            // transitions to StateClosed, StateHijacked, or StateIdle.
            // For HTTP/2, StateActive fires on the transition from zero
            // to one active request, and only transitions away once all
            // active requests are complete. That means that ConnState
            // cannot be used to do per-request work; ConnState only notes
            // the overall state of the connection.
            StateActive
        
            // StateIdle represents a connection that has finished
            // handling a request and is in the keep-alive state, waiting
            // for a new request. Connections transition from StateIdle
            // to either StateActive or StateClosed.
            StateIdle
        
            // StateHijacked represents a hijacked connection.
            // This is a terminal state. It does not transition to StateClosed.
            StateHijacked
        
            // StateClosed represents a closed connection.
            // This is a terminal state. Hijacked connections do not
            // transition to StateClosed.
            StateClosed
        )

        func (ConnState) String

        func (c ConnState) String() string

        A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an HTTP response or the Cookie header of an HTTP request.

        See https://tools.ietf.org/html/rfc6265 for details.

        type Cookie struct {
            Name  string
            Value string
        
            Path       string    // optional
            Domain     string    // optional
            Expires    time.Time // optional
            RawExpires string    // for reading cookies only
        
            // MaxAge=0 means no 'Max-Age' attribute specified.
            // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
            // MaxAge>0 means Max-Age attribute present and given in seconds
            MaxAge   int
            Secure   bool
            HttpOnly bool
            SameSite SameSite
            Raw      string
            Unparsed []string // Raw text of unparsed attribute-value pairs
        }
        

        func (*Cookie) String

        func (c *Cookie) String() string

        String returns the serialization of the cookie for use in a Cookie header (if only Name and Value are set) or a Set-Cookie response header (if other fields are set). If c is nil or c.Name is invalid, the empty string is returned.

        func (*Cookie) Valid

        func (c *Cookie) Valid() error

        Valid reports whether the cookie is valid.

        type CookieJar

        A CookieJar manages storage and use of cookies in HTTP requests.

        Implementations of CookieJar must be safe for concurrent use by multiple goroutines.

        The net/http/cookiejar package provides a CookieJar implementation.

        type CookieJar interface {
            // SetCookies handles the receipt of the cookies in a reply for the
            // given URL.  It may or may not choose to save the cookies, depending
            // on the jar's policy and implementation.
            SetCookies(u *url.URL, cookies []*Cookie)
        
            // Cookies returns the cookies to send in a request for the given URL.
            // It is up to the implementation to honor the standard cookie use
            // restrictions such as in RFC 6265.
            Cookies(u *url.URL) []*Cookie
        }

        type Dir

        A Dir implements FileSystem using the native file system restricted to a specific directory tree.

        While the [FileSystem.Open] method takes '/'-separated paths, a Dir's string value is a filename on the native file system, not a URL, so it is separated by filepath.Separator, which isn't necessarily '/'.

        Note that Dir could expose sensitive files and directories. Dir will follow symlinks pointing out of the directory tree, which can be especially dangerous if serving from a directory in which users are able to create arbitrary symlinks. Dir will also allow access to files and directories starting with a period, which could expose sensitive directories like .git or sensitive files like .htpasswd. To exclude files with a leading period, remove the files/directories from the server or create a custom FileSystem implementation.

        An empty Dir is treated as ".".

        type Dir string

        func (Dir) Open

        func (d Dir) Open(name string) (File, error)

        Open implements FileSystem using os.Open, opening files for reading rooted and relative to the directory d.

        type File

        A File is returned by a FileSystem's Open method and can be served by the FileServer implementation.

        The methods should behave the same as those on an *os.File.

        type File interface {
            io.Closer
            io.Reader
            io.Seeker
            Readdir(count int) ([]fs.FileInfo, error)
            Stat() (fs.FileInfo, error)
        }

        type FileSystem

        A FileSystem implements access to a collection of named files. The elements in a file path are separated by slash ('/', U+002F) characters, regardless of host operating system convention. See the FileServer function to convert a FileSystem to a Handler.

        This interface predates the fs.FS interface, which can be used instead: the FS adapter function converts an fs.FS to a FileSystem.

        type FileSystem interface {
            Open(name string) (File, error)
        }

        func FS

        func FS(fsys fs.FS) FileSystem

        FS converts fsys to a FileSystem implementation, for use with FileServer and NewFileTransport. The files provided by fsys must implement io.Seeker.

        type Flusher

        The Flusher interface is implemented by ResponseWriters that allow an HTTP handler to flush buffered data to the client.

        The default HTTP/1.x and HTTP/2 ResponseWriter implementations support Flusher, but ResponseWriter wrappers may not. Handlers should always test for this ability at runtime.

        Note that even for ResponseWriters that support Flush, if the client is connected through an HTTP proxy, the buffered data may not reach the client until the response completes.

        type Flusher interface {
            // Flush sends any buffered data to the client.
            Flush()
        }

        type Handler

        A Handler responds to an HTTP request.

        [Handler.ServeHTTP] should write reply headers and data to the ResponseWriter and then return. Returning signals that the request is finished; it is not valid to use the ResponseWriter or read from the [Request.Body] after or concurrently with the completion of the ServeHTTP call.

        Depending on the HTTP client software, HTTP protocol version, and any intermediaries between the client and the Go server, it may not be possible to read from the [Request.Body] after writing to the ResponseWriter. Cautious handlers should read the [Request.Body] first, and then reply.

        Except for reading the body, handlers should not modify the provided Request.

        If ServeHTTP panics, the server (the caller of ServeHTTP) assumes that the effect of the panic was isolated to the active request. It recovers the panic, logs a stack trace to the server error log, and either closes the network connection or sends an HTTP/2 RST_STREAM, depending on the HTTP protocol. To abort a handler so the client sees an interrupted response but the server doesn't log an error, panic with the value ErrAbortHandler.

        type Handler interface {
            ServeHTTP(ResponseWriter, *Request)
        }

        func AllowQuerySemicolons

        func AllowQuerySemicolons(h Handler) Handler

        AllowQuerySemicolons returns a handler that serves requests by converting any unescaped semicolons in the URL query to ampersands, and invoking the handler h.

        This restores the pre-Go 1.17 behavior of splitting query parameters on both semicolons and ampersands. (See golang.org/issue/25192). Note that this behavior doesn't match that of many proxies, and the mismatch can lead to security issues.

        AllowQuerySemicolons should be invoked before Request.ParseForm is called.

        func FileServer

        func FileServer(root FileSystem) Handler

        FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.

        As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html".

        To use the operating system's file system implementation, use http.Dir:

        http.Handle("/", http.FileServer(http.Dir("/tmp")))
        

        To use an fs.FS implementation, use http.FileServerFS instead.

        Example

        Code:

        // Simple static webserver:
        log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
        

        Example (DotFileHiding)

        Code:

        package http_test
        
        import (
            "io/fs"
            "log"
            "net/http"
            "strings"
        )
        
        // containsDotFile reports whether name contains a path element starting with a period.
        // The name is assumed to be a delimited by forward slashes, as guaranteed
        // by the http.FileSystem interface.
        func containsDotFile(name string) bool {
            parts := strings.Split(name, "/")
            for _, part := range parts {
                if strings.HasPrefix(part, ".") {
                    return true
                }
            }
            return false
        }
        
        // dotFileHidingFile is the http.File use in dotFileHidingFileSystem.
        // It is used to wrap the Readdir method of http.File so that we can
        // remove files and directories that start with a period from its output.
        type dotFileHidingFile struct {
            http.File
        }
        
        // Readdir is a wrapper around the Readdir method of the embedded File
        // that filters out all files that start with a period in their name.
        func (f dotFileHidingFile) Readdir(n int) (fis []fs.FileInfo, err error) {
            files, err := f.File.Readdir(n)
            for _, file := range files { // Filters out the dot files
                if !strings.HasPrefix(file.Name(), ".") {
                    fis = append(fis, file)
                }
            }
            return
        }
        
        // dotFileHidingFileSystem is an http.FileSystem that hides
        // hidden "dot files" from being served.
        type dotFileHidingFileSystem struct {
            http.FileSystem
        }
        
        // Open is a wrapper around the Open method of the embedded FileSystem
        // that serves a 403 permission error when name has a file or directory
        // with whose name starts with a period in its path.
        func (fsys dotFileHidingFileSystem) Open(name string) (http.File, error) {
            if containsDotFile(name) { // If dot file, return 403 response
                return nil, fs.ErrPermission
            }
        
            file, err := fsys.FileSystem.Open(name)
            if err != nil {
                return nil, err
            }
            return dotFileHidingFile{file}, err
        }
        
        func ExampleFileServer_dotFileHiding() {
            fsys := dotFileHidingFileSystem{http.Dir(".")}
            http.Handle("/", http.FileServer(fsys))
            log.Fatal(http.ListenAndServe(":8080", nil))
        }
        

        Example (StripPrefix)

        Code:

        // To serve a directory on disk (/tmp) under an alternate URL
        // path (/tmpfiles/), use StripPrefix to modify the request
        // URL's path before the FileServer sees it:
        http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
        

        func FileServerFS

        func FileServerFS(root fs.FS) Handler

        FileServerFS returns a handler that serves HTTP requests with the contents of the file system fsys.

        As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html".

        http.Handle("/", http.FileServerFS(fsys))
        

        func MaxBytesHandler

        func MaxBytesHandler(h Handler, n int64) Handler

        MaxBytesHandler returns a Handler that runs h with its ResponseWriter and [Request.Body] wrapped by a MaxBytesReader.

        func NotFoundHandler

        func NotFoundHandler() Handler

        NotFoundHandler returns a simple request handler that replies to each request with a “404 page not found” reply.

        Example

        Code:

        mux := http.NewServeMux()
        
        // Create sample handler to returns 404
        mux.Handle("/resources", http.NotFoundHandler())
        
        // Create sample handler that returns 200
        mux.Handle("/resources/people/", newPeopleHandler())
        
        log.Fatal(http.ListenAndServe(":8080", mux))
        

        func RedirectHandler

        func RedirectHandler(url string, code int) Handler

        RedirectHandler returns a request handler that redirects each request it receives to the given url using the given status code.

        The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.

        func StripPrefix

        func StripPrefix(prefix string, h Handler) Handler

        StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path (and RawPath if set) and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error. The prefix must match exactly: if the prefix in the request contains escaped characters the reply is also an HTTP 404 not found error.

        Example

        Code:

        // To serve a directory on disk (/tmp) under an alternate URL
        // path (/tmpfiles/), use StripPrefix to modify the request
        // URL's path before the FileServer sees it:
        http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
        

        func TimeoutHandler

        func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler

        TimeoutHandler returns a Handler that runs h with the given time limit.

        The new Handler calls h.ServeHTTP to handle each request, but if a call runs for longer than its time limit, the handler responds with a 503 Service Unavailable error and the given message in its body. (If msg is empty, a suitable default message will be sent.) After such a timeout, writes by h to its ResponseWriter will return ErrHandlerTimeout.

        TimeoutHandler supports the Pusher interface but does not support the Hijacker or Flusher interfaces.

        type HandlerFunc

        The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

        type HandlerFunc func(ResponseWriter, *Request)

        func (HandlerFunc) ServeHTTP

        func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)

        ServeHTTP calls f(w, r).

        A Header represents the key-value pairs in an HTTP header.

        The keys should be in canonical form, as returned by CanonicalHeaderKey.

        type Header map[string][]string

        func (Header) Add

        func (h Header) Add(key, value string)

        Add adds the key, value pair to the header. It appends to any existing values associated with key. The key is case insensitive; it is canonicalized by CanonicalHeaderKey.

        func (Header) Clone

        func (h Header) Clone() Header

        Clone returns a copy of h or nil if h is nil.

        func (Header) Del

        func (h Header) Del(key string)

        Del deletes the values associated with key. The key is case insensitive; it is canonicalized by CanonicalHeaderKey.

        func (Header) Get

        func (h Header) Get(key string) string

        Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. Get assumes that all keys are stored in canonical form. To use non-canonical keys, access the map directly.

        func (Header) Set

        func (h Header) Set(key, value string)

        Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey. To use non-canonical keys, assign to the map directly.

        func (Header) Values

        func (h Header) Values(key string) []string

        Values returns all values associated with the given key. It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. To use non-canonical keys, access the map directly. The returned slice is not a copy.

        func (Header) Write

        func (h Header) Write(w io.Writer) error

        Write writes a header in wire format.

        func (Header) WriteSubset

        func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error

        WriteSubset writes a header in wire format. If exclude is not nil, keys where exclude[key] == true are not written. Keys are not canonicalized before checking the exclude map.

        type Hijacker

        The Hijacker interface is implemented by ResponseWriters that allow an HTTP handler to take over the connection.

        The default ResponseWriter for HTTP/1.x connections supports Hijacker, but HTTP/2 connections intentionally do not. ResponseWriter wrappers may also not support Hijacker. Handlers should always test for this ability at runtime.

        type Hijacker interface {
            // Hijack lets the caller take over the connection.
            // After a call to Hijack the HTTP server library
            // will not do anything else with the connection.
            //
            // It becomes the caller's responsibility to manage
            // and close the connection.
            //
            // The returned net.Conn may have read or write deadlines
            // already set, depending on the configuration of the
            // Server. It is the caller's responsibility to set
            // or clear those deadlines as needed.
            //
            // The returned bufio.Reader may contain unprocessed buffered
            // data from the client.
            //
            // After a call to Hijack, the original Request.Body must not
            // be used. The original Request's Context remains valid and
            // is not canceled until the Request's ServeHTTP method
            // returns.
            Hijack() (net.Conn, *bufio.ReadWriter, error)
        }

        Example

        Code:

        http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
            hj, ok := w.(http.Hijacker)
            if !ok {
                http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
                return
            }
            conn, bufrw, err := hj.Hijack()
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }
            // Don't forget to close the connection:
            defer conn.Close()
            bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
            bufrw.Flush()
            s, err := bufrw.ReadString('\n')
            if err != nil {
                log.Printf("error reading string: %v", err)
                return
            }
            fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
            bufrw.Flush()
        })
        

        type MaxBytesError

        MaxBytesError is returned by MaxBytesReader when its read limit is exceeded.

        type MaxBytesError struct {
            Limit int64
        }
        

        func (*MaxBytesError) Error

        func (e *MaxBytesError) Error() string

        type ProtocolError

        ProtocolError represents an HTTP protocol error.

        Deprecated: Not all errors in the http package related to protocol errors are of type ProtocolError.

        type ProtocolError struct {
            ErrorString string
        }
        

        func (*ProtocolError) Error

        func (pe *ProtocolError) Error() string

        func (*ProtocolError) Is

        func (pe *ProtocolError) Is(err error) bool

        Is lets http.ErrNotSupported match errors.ErrUnsupported.

        type PushOptions

        PushOptions describes options for [Pusher.Push].

        type PushOptions struct {
            // Method specifies the HTTP method for the promised request.
            // If set, it must be "GET" or "HEAD". Empty means "GET".
            Method string
        
            // Header specifies additional promised request headers. This cannot
            // include HTTP/2 pseudo header fields like ":path" and ":scheme",
            // which will be added automatically.
            Header Header
        }
        

        type Pusher

        Pusher is the interface implemented by ResponseWriters that support HTTP/2 server push. For more background, see https://tools.ietf.org/html/rfc7540#section-8.2.

        type Pusher interface {
            // Push initiates an HTTP/2 server push. This constructs a synthetic
            // request using the given target and options, serializes that request
            // into a PUSH_PROMISE frame, then dispatches that request using the
            // server's request handler. If opts is nil, default options are used.
            //
            // The target must either be an absolute path (like "/path") or an absolute
            // URL that contains a valid host and the same scheme as the parent request.
            // If the target is a path, it will inherit the scheme and host of the
            // parent request.
            //
            // The HTTP/2 spec disallows recursive pushes and cross-authority pushes.
            // Push may or may not detect these invalid pushes; however, invalid
            // pushes will be detected and canceled by conforming clients.
            //
            // Handlers that wish to push URL X should call Push before sending any
            // data that may trigger a request for URL X. This avoids a race where the
            // client issues requests for X before receiving the PUSH_PROMISE for X.
            //
            // Push will run in a separate goroutine making the order of arrival
            // non-deterministic. Any required synchronization needs to be implemented
            // by the caller.
            //
            // Push returns ErrNotSupported if the client has disabled push or if push
            // is not supported on the underlying connection.
            Push(target string, opts *PushOptions) error
        }

        type Request

        A Request represents an HTTP request received by a server or to be sent by a client.

        The field semantics differ slightly between client and server usage. In addition to the notes on the fields below, see the documentation for Request.Write and RoundTripper.

        type Request struct {
            // Method specifies the HTTP method (GET, POST, PUT, etc.).
            // For client requests, an empty string means GET.
            Method string
        
            // URL specifies either the URI being requested (for server
            // requests) or the URL to access (for client requests).
            //
            // For server requests, the URL is parsed from the URI
            // supplied on the Request-Line as stored in RequestURI.  For
            // most requests, fields other than Path and RawQuery will be
            // empty. (See RFC 7230, Section 5.3)
            //
            // For client requests, the URL's Host specifies the server to
            // connect to, while the Request's Host field optionally
            // specifies the Host header value to send in the HTTP
            // request.
            URL *url.URL
        
            // The protocol version for incoming server requests.
            //
            // For client requests, these fields are ignored. The HTTP
            // client code always uses either HTTP/1.1 or HTTP/2.
            // See the docs on Transport for details.
            Proto      string // "HTTP/1.0"
            ProtoMajor int    // 1
            ProtoMinor int    // 0
        
            // Header contains the request header fields either received
            // by the server or to be sent by the client.
            //
            // If a server received a request with header lines,
            //
            //	Host: example.com
            //	accept-encoding: gzip, deflate
            //	Accept-Language: en-us
            //	fOO: Bar
            //	foo: two
            //
            // then
            //
            //	Header = map[string][]string{
            //		"Accept-Encoding": {"gzip, deflate"},
            //		"Accept-Language": {"en-us"},
            //		"Foo": {"Bar", "two"},
            //	}
            //
            // For incoming requests, the Host header is promoted to the
            // Request.Host field and removed from the Header map.
            //
            // HTTP defines that header names are case-insensitive. The
            // request parser implements this by using CanonicalHeaderKey,
            // making the first character and any characters following a
            // hyphen uppercase and the rest lowercase.
            //
            // For client requests, certain headers such as Content-Length
            // and Connection are automatically written when needed and
            // values in Header may be ignored. See the documentation
            // for the Request.Write method.
            Header Header
        
            // Body is the request's body.
            //
            // For client requests, a nil body means the request has no
            // body, such as a GET request. The HTTP Client's Transport
            // is responsible for calling the Close method.
            //
            // For server requests, the Request Body is always non-nil
            // but will return EOF immediately when no body is present.
            // The Server will close the request body. The ServeHTTP
            // Handler does not need to.
            //
            // Body must allow Read to be called concurrently with Close.
            // In particular, calling Close should unblock a Read waiting
            // for input.
            Body io.ReadCloser
        
            // GetBody defines an optional func to return a new copy of
            // Body. It is used for client requests when a redirect requires
            // reading the body more than once. Use of GetBody still
            // requires setting Body.
            //
            // For server requests, it is unused.
            GetBody func() (io.ReadCloser, error)
        
            // ContentLength records the length of the associated content.
            // The value -1 indicates that the length is unknown.
            // Values >= 0 indicate that the given number of bytes may
            // be read from Body.
            //
            // For client requests, a value of 0 with a non-nil Body is
            // also treated as unknown.
            ContentLength int64
        
            // TransferEncoding lists the transfer encodings from outermost to
            // innermost. An empty list denotes the "identity" encoding.
            // TransferEncoding can usually be ignored; chunked encoding is
            // automatically added and removed as necessary when sending and
            // receiving requests.
            TransferEncoding []string
        
            // Close indicates whether to close the connection after
            // replying to this request (for servers) or after sending this
            // request and reading its response (for clients).
            //
            // For server requests, the HTTP server handles this automatically
            // and this field is not needed by Handlers.
            //
            // For client requests, setting this field prevents re-use of
            // TCP connections between requests to the same hosts, as if
            // Transport.DisableKeepAlives were set.
            Close bool
        
            // For server requests, Host specifies the host on which the
            // URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this
            // is either the value of the "Host" header or the host name
            // given in the URL itself. For HTTP/2, it is the value of the
            // ":authority" pseudo-header field.
            // It may be of the form "host:port". For international domain
            // names, Host may be in Punycode or Unicode form. Use
            // golang.org/x/net/idna to convert it to either format if
            // needed.
            // To prevent DNS rebinding attacks, server Handlers should
            // validate that the Host header has a value for which the
            // Handler considers itself authoritative. The included
            // ServeMux supports patterns registered to particular host
            // names and thus protects its registered Handlers.
            //
            // For client requests, Host optionally overrides the Host
            // header to send. If empty, the Request.Write method uses
            // the value of URL.Host. Host may contain an international
            // domain name.
            Host string
        
            // Form contains the parsed form data, including both the URL
            // field's query parameters and the PATCH, POST, or PUT form data.
            // This field is only available after ParseForm is called.
            // The HTTP client ignores Form and uses Body instead.
            Form url.Values
        
            // PostForm contains the parsed form data from PATCH, POST
            // or PUT body parameters.
            //
            // This field is only available after ParseForm is called.
            // The HTTP client ignores PostForm and uses Body instead.
            PostForm url.Values
        
            // MultipartForm is the parsed multipart form, including file uploads.
            // This field is only available after ParseMultipartForm is called.
            // The HTTP client ignores MultipartForm and uses Body instead.
            MultipartForm *multipart.Form
        
            // Trailer specifies additional headers that are sent after the request
            // body.
            //
            // For server requests, the Trailer map initially contains only the
            // trailer keys, with nil values. (The client declares which trailers it
            // will later send.)  While the handler is reading from Body, it must
            // not reference Trailer. After reading from Body returns EOF, Trailer
            // can be read again and will contain non-nil values, if they were sent
            // by the client.
            //
            // For client requests, Trailer must be initialized to a map containing
            // the trailer keys to later send. The values may be nil or their final
            // values. The ContentLength must be 0 or -1, to send a chunked request.
            // After the HTTP request is sent the map values can be updated while
            // the request body is read. Once the body returns EOF, the caller must
            // not mutate Trailer.
            //
            // Few HTTP clients, servers, or proxies support HTTP trailers.
            Trailer Header
        
            // RemoteAddr allows HTTP servers and other software to record
            // the network address that sent the request, usually for
            // logging. This field is not filled in by ReadRequest and
            // has no defined format. The HTTP server in this package
            // sets RemoteAddr to an "IP:port" address before invoking a
            // handler.
            // This field is ignored by the HTTP client.
            RemoteAddr string
        
            // RequestURI is the unmodified request-target of the
            // Request-Line (RFC 7230, Section 3.1.1) as sent by the client
            // to a server. Usually the URL field should be used instead.
            // It is an error to set this field in an HTTP client request.
            RequestURI string
        
            // TLS allows HTTP servers and other software to record
            // information about the TLS connection on which the request
            // was received. This field is not filled in by ReadRequest.
            // The HTTP server in this package sets the field for
            // TLS-enabled connections before invoking a handler;
            // otherwise it leaves the field nil.
            // This field is ignored by the HTTP client.
            TLS *tls.ConnectionState
        
            // Cancel is an optional channel whose closure indicates that the client
            // request should be regarded as canceled. Not all implementations of
            // RoundTripper may support Cancel.
            //
            // For server requests, this field is not applicable.
            //
            // Deprecated: Set the Request's context with NewRequestWithContext
            // instead. If a Request's Cancel field and context are both
            // set, it is undefined whether Cancel is respected.
            Cancel <-chan struct{}
        
            // Response is the redirect response which caused this request
            // to be created. This field is only populated during client
            // redirects.
            Response *Response
            // contains filtered or unexported fields
        }
        

        func NewRequest

        func NewRequest(method, url string, body io.Reader) (*Request, error)

        NewRequest wraps NewRequestWithContext using context.Background.

        func NewRequestWithContext

        func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)

        NewRequestWithContext returns a new Request given a method, URL, and optional body.

        If the provided body is also an io.Closer, the returned [Request.Body] is set to body and will be closed (possibly asynchronously) by the Client methods Do, Post, and PostForm, and Transport.RoundTrip.

        NewRequestWithContext returns a Request suitable for use with Client.Do or Transport.RoundTrip. To create a request for use with testing a Server Handler, either use the NewRequest function in the net/http/httptest package, use ReadRequest, or manually update the Request fields. For an outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body. See the Request type's documentation for the difference between inbound and outbound request fields.

        If body is of type *bytes.Buffer, *bytes.Reader, or *strings.Reader, the returned request's ContentLength is set to its exact value (instead of -1), GetBody is populated (so 307 and 308 redirects can replay the body), and Body is set to NoBody if the ContentLength is 0.

        func ReadRequest

        func ReadRequest(b *bufio.Reader) (*Request, error)

        ReadRequest reads and parses an incoming request from b.

        ReadRequest is a low-level function and should only be used for specialized applications; most code should use the Server to read requests and handle them via the Handler interface. ReadRequest only supports HTTP/1.x requests. For HTTP/2, use golang.org/x/net/http2.

        func (*Request) AddCookie

        func (r *Request) AddCookie(c *Cookie)

        AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, AddCookie does not attach more than one Cookie header field. That means all cookies, if any, are written into the same line, separated by semicolon. AddCookie only sanitizes c's name and value, and does not sanitize a Cookie header already present in the request.

        func (*Request) BasicAuth

        func (r *Request) BasicAuth() (username, password string, ok bool)

        BasicAuth returns the username and password provided in the request's Authorization header, if the request uses HTTP Basic Authentication. See RFC 2617, Section 2.

        func (*Request) Clone

        func (r *Request) Clone(ctx context.Context) *Request

        Clone returns a deep copy of r with its context changed to ctx. The provided ctx must be non-nil.

        For an outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body.

        func (*Request) Context

        func (r *Request) Context() context.Context

        Context returns the request's context. To change the context, use Request.Clone or Request.WithContext.

        The returned context is always non-nil; it defaults to the background context.

        For outgoing client requests, the context controls cancellation.

        For incoming server requests, the context is canceled when the client's connection closes, the request is canceled (with HTTP/2), or when the ServeHTTP method returns.

        func (*Request) Cookie

        func (r *Request) Cookie(name string) (*Cookie, error)

        Cookie returns the named cookie provided in the request or ErrNoCookie if not found. If multiple cookies match the given name, only one cookie will be returned.

        func (*Request) Cookies

        func (r *Request) Cookies() []*Cookie

        Cookies parses and returns the HTTP cookies sent with the request.

        func (*Request) FormFile

        func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

        FormFile returns the first file for the provided form key. FormFile calls Request.ParseMultipartForm and Request.ParseForm if necessary.

        func (*Request) FormValue

        func (r *Request) FormValue(key string) string

        FormValue returns the first value for the named component of the query. The precedence order:

        1. application/x-www-form-urlencoded form body (POST, PUT, PATCH only)
        2. query parameters (always)
        3. multipart/form-data form body (always)

        FormValue calls Request.ParseMultipartForm and Request.ParseForm if necessary and ignores any errors returned by these functions. If key is not present, FormValue returns the empty string. To access multiple values of the same key, call ParseForm and then inspect [Request.Form] directly.

        func (*Request) MultipartReader

        func (r *Request) MultipartReader() (*multipart.Reader, error)

        MultipartReader returns a MIME multipart reader if this is a multipart/form-data or a multipart/mixed POST request, else returns nil and an error. Use this function instead of Request.ParseMultipartForm to process the request body as a stream.

        func (*Request) ParseForm

        func (r *Request) ParseForm() error

        ParseForm populates r.Form and r.PostForm.

        For all requests, ParseForm parses the raw query from the URL and updates r.Form.

        For POST, PUT, and PATCH requests, it also reads the request body, parses it as a form and puts the results into both r.PostForm and r.Form. Request body parameters take precedence over URL query string values in r.Form.

        If the request Body's size has not already been limited by MaxBytesReader, the size is capped at 10MB.

        For other HTTP methods, or when the Content-Type is not application/x-www-form-urlencoded, the request Body is not read, and r.PostForm is initialized to a non-nil, empty value.

        Request.ParseMultipartForm calls ParseForm automatically. ParseForm is idempotent.

        func (*Request) ParseMultipartForm

        func (r *Request) ParseMultipartForm(maxMemory int64) error

        ParseMultipartForm parses a request body as multipart/form-data. The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files. ParseMultipartForm calls Request.ParseForm if necessary. If ParseForm returns an error, ParseMultipartForm returns it but also continues parsing the request body. After one call to ParseMultipartForm, subsequent calls have no effect.

        func (*Request) PathValue

        func (r *Request) PathValue(name string) string

        PathValue returns the value for the named path wildcard in the ServeMux pattern that matched the request. It returns the empty string if the request was not matched against a pattern or there is no such wildcard in the pattern.

        func (*Request) PostFormValue

        func (r *Request) PostFormValue(key string) string

        PostFormValue returns the first value for the named component of the POST, PUT, or PATCH request body. URL query parameters are ignored. PostFormValue calls Request.ParseMultipartForm and Request.ParseForm if necessary and ignores any errors returned by these functions. If key is not present, PostFormValue returns the empty string.

        func (*Request) ProtoAtLeast

        func (r *Request) ProtoAtLeast(major, minor int) bool

        ProtoAtLeast reports whether the HTTP protocol used in the request is at least major.minor.

        func (*Request) Referer

        func (r *Request) Referer() string

        Referer returns the referring URL, if sent in the request.

        Referer is misspelled as in the request itself, a mistake from the earliest days of HTTP. This value can also be fetched from the Header map as Header["Referer"]; the benefit of making it available as a method is that the compiler can diagnose programs that use the alternate (correct English) spelling req.Referrer() but cannot diagnose programs that use Header["Referrer"].

        func (*Request) SetBasicAuth

        func (r *Request) SetBasicAuth(username, password string)

        SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.

        With HTTP Basic Authentication the provided username and password are not encrypted. It should generally only be used in an HTTPS request.

        The username may not contain a colon. Some protocols may impose additional requirements on pre-escaping the username and password. For instance, when used with OAuth2, both arguments must be URL encoded first with url.QueryEscape.

        func (*Request) SetPathValue

        func (r *Request) SetPathValue(name, value string)

        SetPathValue sets name to value, so that subsequent calls to r.PathValue(name) return value.

        func (*Request) UserAgent

        func (r *Request) UserAgent() string

        UserAgent returns the client's User-Agent, if sent in the request.

        func (*Request) WithContext

        func (r *Request) WithContext(ctx context.Context) *Request

        WithContext returns a shallow copy of r with its context changed to ctx. The provided ctx must be non-nil.

        For outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body.

        To create a new request with a context, use NewRequestWithContext. To make a deep copy of a request with a new context, use Request.Clone.

        func (*Request) Write

        func (r *Request) Write(w io.Writer) error

        Write writes an HTTP/1.1 request, which is the header and body, in wire format. This method consults the following fields of the request:

        Host
        URL
        Method (defaults to "GET")
        Header
        ContentLength
        TransferEncoding
        Body
        

        If Body is present, Content-Length is <= 0 and [Request.TransferEncoding] hasn't been set to "identity", Write adds "Transfer-Encoding: chunked" to the header. Body is closed after it is sent.

        func (*Request) WriteProxy

        func (r *Request) WriteProxy(w io.Writer) error

        WriteProxy is like Request.Write but writes the request in the form expected by an HTTP proxy. In particular, Request.WriteProxy writes the initial Request-URI line of the request with an absolute URI, per section 5.3 of RFC 7230, including the scheme and host. In either case, WriteProxy also writes a Host header, using either r.Host or r.URL.Host.

        type Response

        Response represents the response from an HTTP request.

        The Client and Transport return Responses from servers once the response headers have been received. The response body is streamed on demand as the Body field is read.

        type Response struct {
            Status     string // e.g. "200 OK"
            StatusCode int    // e.g. 200
            Proto      string // e.g. "HTTP/1.0"
            ProtoMajor int    // e.g. 1
            ProtoMinor int    // e.g. 0
        
            // Header maps header keys to values. If the response had multiple
            // headers with the same key, they may be concatenated, with comma
            // delimiters.  (RFC 7230, section 3.2.2 requires that multiple headers
            // be semantically equivalent to a comma-delimited sequence.) When
            // Header values are duplicated by other fields in this struct (e.g.,
            // ContentLength, TransferEncoding, Trailer), the field values are
            // authoritative.
            //
            // Keys in the map are canonicalized (see CanonicalHeaderKey).
            Header Header
        
            // Body represents the response body.
            //
            // The response body is streamed on demand as the Body field
            // is read. If the network connection fails or the server
            // terminates the response, Body.Read calls return an error.
            //
            // The http Client and Transport guarantee that Body is always
            // non-nil, even on responses without a body or responses with
            // a zero-length body. It is the caller's responsibility to
            // close Body. The default HTTP client's Transport may not
            // reuse HTTP/1.x "keep-alive" TCP connections if the Body is
            // not read to completion and closed.
            //
            // The Body is automatically dechunked if the server replied
            // with a "chunked" Transfer-Encoding.
            //
            // As of Go 1.12, the Body will also implement io.Writer
            // on a successful "101 Switching Protocols" response,
            // as used by WebSockets and HTTP/2's "h2c" mode.
            Body io.ReadCloser
        
            // ContentLength records the length of the associated content. The
            // value -1 indicates that the length is unknown. Unless Request.Method
            // is "HEAD", values >= 0 indicate that the given number of bytes may
            // be read from Body.
            ContentLength int64
        
            // Contains transfer encodings from outer-most to inner-most. Value is
            // nil, means that "identity" encoding is used.
            TransferEncoding []string
        
            // Close records whether the header directed that the connection be
            // closed after reading Body. The value is advice for clients: neither
            // ReadResponse nor Response.Write ever closes a connection.
            Close bool
        
            // Uncompressed reports whether the response was sent compressed but
            // was decompressed by the http package. When true, reading from
            // Body yields the uncompressed content instead of the compressed
            // content actually set from the server, ContentLength is set to -1,
            // and the "Content-Length" and "Content-Encoding" fields are deleted
            // from the responseHeader. To get the original response from
            // the server, set Transport.DisableCompression to true.
            Uncompressed bool
        
            // Trailer maps trailer keys to values in the same
            // format as Header.
            //
            // The Trailer initially contains only nil values, one for
            // each key specified in the server's "Trailer" header
            // value. Those values are not added to Header.
            //
            // Trailer must not be accessed concurrently with Read calls
            // on the Body.
            //
            // After Body.Read has returned io.EOF, Trailer will contain
            // any trailer values sent by the server.
            Trailer Header
        
            // Request is the request that was sent to obtain this Response.
            // Request's Body is nil (having already been consumed).
            // This is only populated for Client requests.
            Request *Request
        
            // TLS contains information about the TLS connection on which the
            // response was received. It is nil for unencrypted responses.
            // The pointer is shared between responses and should not be
            // modified.
            TLS *tls.ConnectionState
        }
        

        func Get

        func Get(url string) (resp *Response, err error)

        Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect, up to a maximum of 10 redirects:

        301 (Moved Permanently)
        302 (Found)
        303 (See Other)
        307 (Temporary Redirect)
        308 (Permanent Redirect)
        

        An error is returned if there were too many redirects or if there was an HTTP protocol error. A non-2xx response doesn't cause an error. Any returned error will be of type *url.Error. The url.Error value's Timeout method will report true if the request timed out.

        When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.

        Get is a wrapper around DefaultClient.Get.

        To make a request with custom headers, use NewRequest and DefaultClient.Do.

        To make a request with a specified context.Context, use NewRequestWithContext and DefaultClient.Do.

        Example

        Code:

        res, err := http.Get("http://www.google.com/robots.txt")
        if err != nil {
            log.Fatal(err)
        }
        body, err := io.ReadAll(res.Body)
        res.Body.Close()
        if res.StatusCode > 299 {
            log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body)
        }
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s", body)
        
        func Head(url string) (resp *Response, err error)

        Head issues a HEAD to the specified URL. If the response is one of the following redirect codes, Head follows the redirect, up to a maximum of 10 redirects:

        301 (Moved Permanently)
        302 (Found)
        303 (See Other)
        307 (Temporary Redirect)
        308 (Permanent Redirect)
        

        Head is a wrapper around DefaultClient.Head.

        To make a request with a specified context.Context, use NewRequestWithContext and DefaultClient.Do.

        func Post

        func Post(url, contentType string, body io.Reader) (resp *Response, err error)

        Post issues a POST to the specified URL.

        Caller should close resp.Body when done reading from it.

        If the provided body is an io.Closer, it is closed after the request.

        Post is a wrapper around DefaultClient.Post.

        To set custom headers, use NewRequest and DefaultClient.Do.

        See the Client.Do method documentation for details on how redirects are handled.

        To make a request with a specified context.Context, use NewRequestWithContext and DefaultClient.Do.

        func PostForm

        func PostForm(url string, data url.Values) (resp *Response, err error)

        PostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body.

        The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use NewRequest and DefaultClient.Do.

        When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.

        PostForm is a wrapper around DefaultClient.PostForm.

        See the Client.Do method documentation for details on how redirects are handled.

        To make a request with a specified context.Context, use NewRequestWithContext and DefaultClient.Do.

        func ReadResponse

        func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)

        ReadResponse reads and returns an HTTP response from r. The req parameter optionally specifies the Request that corresponds to this Response. If nil, a GET request is assumed. Clients must call resp.Body.Close when finished reading resp.Body. After that call, clients can inspect resp.Trailer to find key/value pairs included in the response trailer.

        func (*Response) Cookies

        func (r *Response) Cookies() []*Cookie

        Cookies parses and returns the cookies set in the Set-Cookie headers.

        func (*Response) Location

        func (r *Response) Location() (*url.URL, error)

        Location returns the URL of the response's "Location" header, if present. Relative redirects are resolved relative to [Response.Request]. ErrNoLocation is returned if no Location header is present.

        func (*Response) ProtoAtLeast

        func (r *Response) ProtoAtLeast(major, minor int) bool

        ProtoAtLeast reports whether the HTTP protocol used in the response is at least major.minor.

        func (*Response) Write

        func (r *Response) Write(w io.Writer) error

        Write writes r to w in the HTTP/1.x server response format, including the status line, headers, body, and optional trailer.

        This method consults the following fields of the response r:

        StatusCode
        ProtoMajor
        ProtoMinor
        Request.Method
        TransferEncoding
        Trailer
        Body
        ContentLength
        Header, values for non-canonical keys will have unpredictable behavior
        

        The Response Body is closed after it is sent.

        type ResponseController

        A ResponseController is used by an HTTP handler to control the response.

        A ResponseController may not be used after the [Handler.ServeHTTP] method has returned.

        type ResponseController struct {
            // contains filtered or unexported fields
        }
        

        func NewResponseController

        func NewResponseController(rw ResponseWriter) *ResponseController

        NewResponseController creates a ResponseController for a request.

        The ResponseWriter should be the original value passed to the [Handler.ServeHTTP] method, or have an Unwrap method returning the original ResponseWriter.

        If the ResponseWriter implements any of the following methods, the ResponseController will call them as appropriate:

        Flush()
        FlushError() error // alternative Flush returning an error
        Hijack() (net.Conn, *bufio.ReadWriter, error)
        SetReadDeadline(deadline time.Time) error
        SetWriteDeadline(deadline time.Time) error
        EnableFullDuplex() error
        

        If the ResponseWriter does not support a method, ResponseController returns an error matching ErrNotSupported.

        func (*ResponseController) EnableFullDuplex

        func (c *ResponseController) EnableFullDuplex() error

        EnableFullDuplex indicates that the request handler will interleave reads from [Request.Body] with writes to the ResponseWriter.

        For HTTP/1 requests, the Go HTTP server by default consumes any unread portion of the request body before beginning to write the response, preventing handlers from concurrently reading from the request and writing the response. Calling EnableFullDuplex disables this behavior and permits handlers to continue to read from the request while concurrently writing the response.

        For HTTP/2 requests, the Go HTTP server always permits concurrent reads and responses.

        func (*ResponseController) Flush

        func (c *ResponseController) Flush() error

        Flush flushes buffered data to the client.

        func (*ResponseController) Hijack

        func (c *ResponseController) Hijack() (net.Conn, *bufio.ReadWriter, error)

        Hijack lets the caller take over the connection. See the Hijacker interface for details.

        func (*ResponseController) SetReadDeadline

        func (c *ResponseController) SetReadDeadline(deadline time.Time) error

        SetReadDeadline sets the deadline for reading the entire request, including the body. Reads from the request body after the deadline has been exceeded will return an error. A zero value means no deadline.

        Setting the read deadline after it has been exceeded will not extend it.

        func (*ResponseController) SetWriteDeadline

        func (c *ResponseController) SetWriteDeadline(deadline time.Time) error

        SetWriteDeadline sets the deadline for writing the response. Writes to the response body after the deadline has been exceeded will not block, but may succeed if the data has been buffered. A zero value means no deadline.

        Setting the write deadline after it has been exceeded will not extend it.

        type ResponseWriter

        A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.

        A ResponseWriter may not be used after [Handler.ServeHTTP] has returned.

        type ResponseWriter interface {
            // Header returns the header map that will be sent by
            // [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which
            // [Handler] implementations can set HTTP trailers.
            //
            // Changing the header map after a call to [ResponseWriter.WriteHeader] (or
            // [ResponseWriter.Write]) has no effect unless the HTTP status code was of the
            // 1xx class or the modified headers are trailers.
            //
            // There are two ways to set Trailers. The preferred way is to
            // predeclare in the headers which trailers you will later
            // send by setting the "Trailer" header to the names of the
            // trailer keys which will come later. In this case, those
            // keys of the Header map are treated as if they were
            // trailers. See the example. The second way, for trailer
            // keys not known to the [Handler] until after the first [ResponseWriter.Write],
            // is to prefix the [Header] map keys with the [TrailerPrefix]
            // constant value.
            //
            // To suppress automatic response headers (such as "Date"), set
            // their value to nil.
            Header() Header
        
            // Write writes the data to the connection as part of an HTTP reply.
            //
            // If [ResponseWriter.WriteHeader] has not yet been called, Write calls
            // WriteHeader(http.StatusOK) before writing the data. If the Header
            // does not contain a Content-Type line, Write adds a Content-Type set
            // to the result of passing the initial 512 bytes of written data to
            // [DetectContentType]. Additionally, if the total size of all written
            // data is under a few KB and there are no Flush calls, the
            // Content-Length header is added automatically.
            //
            // Depending on the HTTP protocol version and the client, calling
            // Write or WriteHeader may prevent future reads on the
            // Request.Body. For HTTP/1.x requests, handlers should read any
            // needed request body data before writing the response. Once the
            // headers have been flushed (due to either an explicit Flusher.Flush
            // call or writing enough data to trigger a flush), the request body
            // may be unavailable. For HTTP/2 requests, the Go HTTP server permits
            // handlers to continue to read the request body while concurrently
            // writing the response. However, such behavior may not be supported
            // by all HTTP/2 clients. Handlers should read before writing if
            // possible to maximize compatibility.
            Write([]byte) (int, error)
        
            // WriteHeader sends an HTTP response header with the provided
            // status code.
            //
            // If WriteHeader is not called explicitly, the first call to Write
            // will trigger an implicit WriteHeader(http.StatusOK).
            // Thus explicit calls to WriteHeader are mainly used to
            // send error codes or 1xx informational responses.
            //
            // The provided code must be a valid HTTP 1xx-5xx status code.
            // Any number of 1xx headers may be written, followed by at most
            // one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx
            // headers may be buffered. Use the Flusher interface to send
            // buffered data. The header map is cleared when 2xx-5xx headers are
            // sent, but not with 1xx headers.
            //
            // The server will automatically send a 100 (Continue) header
            // on the first read from the request body if the request has
            // an "Expect: 100-continue" header.
            WriteHeader(statusCode int)
        }

        Example (Trailers)

        HTTP Trailers are a set of key/value pairs like headers that come after the HTTP response, instead of before.

        Code:

        mux := http.NewServeMux()
        mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
            // Before any call to WriteHeader or Write, declare
            // the trailers you will set during the HTTP
            // response. These three headers are actually sent in
            // the trailer.
            w.Header().Set("Trailer", "AtEnd1, AtEnd2")
            w.Header().Add("Trailer", "AtEnd3")
        
            w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
            w.WriteHeader(http.StatusOK)
        
            w.Header().Set("AtEnd1", "value 1")
            io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
            w.Header().Set("AtEnd2", "value 2")
            w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.
        })
        

        type RoundTripper

        RoundTripper is an interface representing the ability to execute a single HTTP transaction, obtaining the Response for a given Request.

        A RoundTripper must be safe for concurrent use by multiple goroutines.

        type RoundTripper interface {
            // RoundTrip executes a single HTTP transaction, returning
            // a Response for the provided Request.
            //
            // RoundTrip should not attempt to interpret the response. In
            // particular, RoundTrip must return err == nil if it obtained
            // a response, regardless of the response's HTTP status code.
            // A non-nil err should be reserved for failure to obtain a
            // response. Similarly, RoundTrip should not attempt to
            // handle higher-level protocol details such as redirects,
            // authentication, or cookies.
            //
            // RoundTrip should not modify the request, except for
            // consuming and closing the Request's Body. RoundTrip may
            // read fields of the request in a separate goroutine. Callers
            // should not mutate or reuse the request until the Response's
            // Body has been closed.
            //
            // RoundTrip must always close the body, including on errors,
            // but depending on the implementation may do so in a separate
            // goroutine even after RoundTrip returns. This means that
            // callers wanting to reuse the body for subsequent requests
            // must arrange to wait for the Close call before doing so.
            //
            // The Request's URL and Header fields must be initialized.
            RoundTrip(*Request) (*Response, error)
        }

        DefaultTransport is the default implementation of Transport and is used by DefaultClient. It establishes network connections as needed and caches them for reuse by subsequent calls. It uses HTTP proxies as directed by the environment variables HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions thereof).

        var DefaultTransport RoundTripper = &Transport{
            Proxy: ProxyFromEnvironment,
            DialContext: defaultTransportDialContext(&net.Dialer{
                Timeout:   30 * time.Second,
                KeepAlive: 30 * time.Second,
            }),
            ForceAttemptHTTP2:     true,
            MaxIdleConns:          100,
            IdleConnTimeout:       90 * time.Second,
            TLSHandshakeTimeout:   10 * time.Second,
            ExpectContinueTimeout: 1 * time.Second,
        }

        func NewFileTransport

        func NewFileTransport(fs FileSystem) RoundTripper

        NewFileTransport returns a new RoundTripper, serving the provided FileSystem. The returned RoundTripper ignores the URL host in its incoming requests, as well as most other properties of the request.

        The typical use case for NewFileTransport is to register the "file" protocol with a Transport, as in:

        t := &http.Transport{}
        t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
        c := &http.Client{Transport: t}
        res, err := c.Get("file:///etc/passwd")
        ...
        

        func NewFileTransportFS

        func NewFileTransportFS(fsys fs.FS) RoundTripper

        NewFileTransportFS returns a new RoundTripper, serving the provided file system fsys. The returned RoundTripper ignores the URL host in its incoming requests, as well as most other properties of the request.

        The typical use case for NewFileTransportFS is to register the "file" protocol with a Transport, as in:

        fsys := os.DirFS("/")
        t := &http.Transport{}
        t.RegisterProtocol("file", http.NewFileTransportFS(fsys))
        c := &http.Client{Transport: t}
        res, err := c.Get("file:///etc/passwd")
        ...
        

        type SameSite

        SameSite allows a server to define a cookie attribute making it impossible for the browser to send this cookie along with cross-site requests. The main goal is to mitigate the risk of cross-origin information leakage, and provide some protection against cross-site request forgery attacks.

        See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.

        type SameSite int
        const (
            SameSiteDefaultMode SameSite = iota + 1
            SameSiteLaxMode
            SameSiteStrictMode
            SameSiteNoneMode
        )

        type ServeMux

        ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.

        Patterns

        Patterns can match the method, host and path of a request. Some examples:

        • "/index.html" matches the path "/index.html" for any host and method.
        • "GET /static/" matches a GET request whose path begins with "/static/".
        • "example.com/" matches any request to the host "example.com".
        • "example.com/{$}" matches requests with host "example.com" and path "/".
        • "/b/{bucket}/o/{objectname...}" matches paths whose first segment is "b" and whose third segment is "o". The name "bucket" denotes the second segment and "objectname" denotes the remainder of the path.

        In general, a pattern looks like

        [METHOD ][HOST]/[PATH]
        

        All three parts are optional; "/" is a valid pattern. If METHOD is present, it must be followed by a single space.

        Literal (that is, non-wildcard) parts of a pattern match the corresponding parts of a request case-sensitively.

        A pattern with no method matches every method. A pattern with the method GET matches both GET and HEAD requests. Otherwise, the method must match exactly.

        A pattern with no host matches every host. A pattern with a host matches URLs on that host only.

        A path can include wildcard segments of the form {NAME} or {NAME...}. For example, "/b/{bucket}/o/{objectname...}". The wildcard name must be a valid Go identifier. Wildcards must be full path segments: they must be preceded by a slash and followed by either a slash or the end of the string. For example, "/b_{bucket}" is not a valid pattern.

        Normally a wildcard matches only a single path segment, ending at the next literal slash (not %2F) in the request URL. But if the "..." is present, then the wildcard matches the remainder of the URL path, including slashes. (Therefore it is invalid for a "..." wildcard to appear anywhere but at the end of a pattern.) The match for a wildcard can be obtained by calling Request.PathValue with the wildcard's name. A trailing slash in a path acts as an anonymous "..." wildcard.

        The special wildcard {$} matches only the end of the URL. For example, the pattern "/{$}" matches only the path "/", whereas the pattern "/" matches every path.

        For matching, both pattern paths and incoming request paths are unescaped segment by segment. So, for example, the path "/a%2Fb/100%25" is treated as having two segments, "a/b" and "100%". The pattern "/a%2fb/" matches it, but the pattern "/a/b/" does not.

        Precedence

        If two or more patterns match a request, then the most specific pattern takes precedence. A pattern P1 is more specific than P2 if P1 matches a strict subset of P2’s requests; that is, if P2 matches all the requests of P1 and more. If neither is more specific, then the patterns conflict. There is one exception to this rule, for backwards compatibility: if two patterns would otherwise conflict and one has a host while the other does not, then the pattern with the host takes precedence. If a pattern passed ServeMux.Handle or ServeMux.HandleFunc conflicts with another pattern that is already registered, those functions panic.

        As an example of the general rule, "/images/thumbnails/" is more specific than "/images/", so both can be registered. The former matches paths beginning with "/images/thumbnails/" and the latter will match any other path in the "/images/" subtree.

        As another example, consider the patterns "GET /" and "/index.html": both match a GET request for "/index.html", but the former pattern matches all other GET and HEAD requests, while the latter matches any request for "/index.html" that uses a different method. The patterns conflict.

        Trailing-slash redirection

        Consider a ServeMux with a handler for a subtree, registered using a trailing slash or "..." wildcard. If the ServeMux receives a request for the subtree root without a trailing slash, it redirects the request by adding the trailing slash. This behavior can be overridden with a separate registration for the path without the trailing slash or "..." wildcard. For example, registering "/images/" causes ServeMux to redirect a request for "/images" to "/images/", unless "/images" has been registered separately.

        Request sanitizing

        ServeMux also takes care of sanitizing the URL request path and the Host header, stripping the port number and redirecting any request containing . or .. segments or repeated slashes to an equivalent, cleaner URL.

        Compatibility

        The pattern syntax and matching behavior of ServeMux changed significantly in Go 1.22. To restore the old behavior, set the GODEBUG environment variable to "httpmuxgo121=1". This setting is read once, at program startup; changes during execution will be ignored.

        The backwards-incompatible changes include:

        • Wildcards are just ordinary literal path segments in 1.21. For example, the pattern "/{x}" will match only that path in 1.21, but will match any one-segment path in 1.22.
        • In 1.21, no pattern was rejected, unless it was empty or conflicted with an existing pattern. In 1.22, syntactically invalid patterns will cause ServeMux.Handle and ServeMux.HandleFunc to panic. For example, in 1.21, the patterns "/{" and "/a{x}" match themselves, but in 1.22 they are invalid and will cause a panic when registered.
        • In 1.22, each segment of a pattern is unescaped; this was not done in 1.21. For example, in 1.22 the pattern "/%61" matches the path "/a" ("%61" being the URL escape sequence for "a"), but in 1.21 it would match only the path "/%2561" (where "%25" is the escape for the percent sign).
        • When matching patterns to paths, in 1.22 each segment of the path is unescaped; in 1.21, the entire path is unescaped. This change mostly affects how paths with %2F escapes adjacent to slashes are treated. See https://go.dev/issue/21955 for details.
        type ServeMux struct {
            // contains filtered or unexported fields
        }
        

        func NewServeMux

        func NewServeMux() *ServeMux

        NewServeMux allocates and returns a new ServeMux.

        func (*ServeMux) Handle

        func (mux *ServeMux) Handle(pattern string, handler Handler)

        Handle registers the handler for the given pattern. If the given pattern conflicts, with one that is already registered, Handle panics.

        Example

        Code:

        mux := http.NewServeMux()
        mux.Handle("/api/", apiHandler{})
        mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
            // The "/" pattern matches everything, so we need to check
            // that we're at the root here.
            if req.URL.Path != "/" {
                http.NotFound(w, req)
                return
            }
            fmt.Fprintf(w, "Welcome to the home page!")
        })
        

        func (*ServeMux) HandleFunc

        func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))

        HandleFunc registers the handler function for the given pattern. If the given pattern conflicts, with one that is already registered, HandleFunc panics.

        func (*ServeMux) Handler

        func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)

        Handler returns the handler to use for the given request, consulting r.Method, r.Host, and r.URL.Path. It always returns a non-nil handler. If the path is not in its canonical form, the handler will be an internally-generated handler that redirects to the canonical path. If the host contains a port, it is ignored when matching handlers.

        The path and host are used unchanged for CONNECT requests.

        Handler also returns the registered pattern that matches the request or, in the case of internally-generated redirects, the path that will match after following the redirect.

        If there is no registered handler that applies to the request, Handler returns a “page not found” handler and an empty pattern.

        func (*ServeMux) ServeHTTP

        func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)

        ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL.

        type Server

        A Server defines parameters for running an HTTP server. The zero value for Server is a valid configuration.

        type Server struct {
            // Addr optionally specifies the TCP address for the server to listen on,
            // in the form "host:port". If empty, ":http" (port 80) is used.
            // The service names are defined in RFC 6335 and assigned by IANA.
            // See net.Dial for details of the address format.
            Addr string
        
            Handler Handler // handler to invoke, http.DefaultServeMux if nil
        
            // DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
            // otherwise responds with 200 OK and Content-Length: 0.
            DisableGeneralOptionsHandler bool
        
            // TLSConfig optionally provides a TLS configuration for use
            // by ServeTLS and ListenAndServeTLS. Note that this value is
            // cloned by ServeTLS and ListenAndServeTLS, so it's not
            // possible to modify the configuration with methods like
            // tls.Config.SetSessionTicketKeys. To use
            // SetSessionTicketKeys, use Server.Serve with a TLS Listener
            // instead.
            TLSConfig *tls.Config
        
            // ReadTimeout is the maximum duration for reading the entire
            // request, including the body. A zero or negative value means
            // there will be no timeout.
            //
            // Because ReadTimeout does not let Handlers make per-request
            // decisions on each request body's acceptable deadline or
            // upload rate, most users will prefer to use
            // ReadHeaderTimeout. It is valid to use them both.
            ReadTimeout time.Duration
        
            // ReadHeaderTimeout is the amount of time allowed to read
            // request headers. The connection's read deadline is reset
            // after reading the headers and the Handler can decide what
            // is considered too slow for the body. If ReadHeaderTimeout
            // is zero, the value of ReadTimeout is used. If both are
            // zero, there is no timeout.
            ReadHeaderTimeout time.Duration
        
            // WriteTimeout is the maximum duration before timing out
            // writes of the response. It is reset whenever a new
            // request's header is read. Like ReadTimeout, it does not
            // let Handlers make decisions on a per-request basis.
            // A zero or negative value means there will be no timeout.
            WriteTimeout time.Duration
        
            // IdleTimeout is the maximum amount of time to wait for the
            // next request when keep-alives are enabled. If IdleTimeout
            // is zero, the value of ReadTimeout is used. If both are
            // zero, there is no timeout.
            IdleTimeout time.Duration
        
            // MaxHeaderBytes controls the maximum number of bytes the
            // server will read parsing the request header's keys and
            // values, including the request line. It does not limit the
            // size of the request body.
            // If zero, DefaultMaxHeaderBytes is used.
            MaxHeaderBytes int
        
            // TLSNextProto optionally specifies a function to take over
            // ownership of the provided TLS connection when an ALPN
            // protocol upgrade has occurred. The map key is the protocol
            // name negotiated. The Handler argument should be used to
            // handle HTTP requests and will initialize the Request's TLS
            // and RemoteAddr if not already set. The connection is
            // automatically closed when the function returns.
            // If TLSNextProto is not nil, HTTP/2 support is not enabled
            // automatically.
            TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
        
            // ConnState specifies an optional callback function that is
            // called when a client connection changes state. See the
            // ConnState type and associated constants for details.
            ConnState func(net.Conn, ConnState)
        
            // ErrorLog specifies an optional logger for errors accepting
            // connections, unexpected behavior from handlers, and
            // underlying FileSystem errors.
            // If nil, logging is done via the log package's standard logger.
            ErrorLog *log.Logger
        
            // BaseContext optionally specifies a function that returns
            // the base context for incoming requests on this server.
            // The provided Listener is the specific Listener that's
            // about to start accepting requests.
            // If BaseContext is nil, the default is context.Background().
            // If non-nil, it must return a non-nil context.
            BaseContext func(net.Listener) context.Context
        
            // ConnContext optionally specifies a function that modifies
            // the context used for a new connection c. The provided ctx
            // is derived from the base context and has a ServerContextKey
            // value.
            ConnContext func(ctx context.Context, c net.Conn) context.Context
            // contains filtered or unexported fields
        }
        

        func (*Server) Close

        func (srv *Server) Close() error

        Close immediately closes all active net.Listeners and any connections in state StateNew, StateActive, or StateIdle. For a graceful shutdown, use Server.Shutdown.

        Close does not attempt to close (and does not even know about) any hijacked connections, such as WebSockets.

        Close returns any error returned from closing the Server's underlying Listener(s).

        func (*Server) ListenAndServe

        func (srv *Server) ListenAndServe() error

        ListenAndServe listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.

        If srv.Addr is blank, ":http" is used.

        ListenAndServe always returns a non-nil error. After Server.Shutdown or Server.Close, the returned error is ErrServerClosed.

        func (*Server) ListenAndServeTLS

        func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error

        ListenAndServeTLS listens on the TCP network address srv.Addr and then calls ServeTLS to handle requests on incoming TLS connections. Accepted connections are configured to enable TCP keep-alives.

        Filenames containing a certificate and matching private key for the server must be provided if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

        If srv.Addr is blank, ":https" is used.

        ListenAndServeTLS always returns a non-nil error. After Server.Shutdown or Server.Close, the returned error is ErrServerClosed.

        func (*Server) RegisterOnShutdown

        func (srv *Server) RegisterOnShutdown(f func())

        RegisterOnShutdown registers a function to call on Server.Shutdown. This can be used to gracefully shutdown connections that have undergone ALPN protocol upgrade or that have been hijacked. This function should start protocol-specific graceful shutdown, but should not wait for shutdown to complete.

        func (*Server) Serve

        func (srv *Server) Serve(l net.Listener) error

        Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call srv.Handler to reply to them.

        HTTP/2 support is only enabled if the Listener returns *tls.Conn connections and they were configured with "h2" in the TLS Config.NextProtos.

        Serve always returns a non-nil error and closes l. After Server.Shutdown or Server.Close, the returned error is ErrServerClosed.

        func (*Server) ServeTLS

        func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error

        ServeTLS accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines perform TLS setup and then read requests, calling srv.Handler to reply to them.

        Files containing a certificate and matching private key for the server must be provided if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

        ServeTLS always returns a non-nil error. After Server.Shutdown or Server.Close, the returned error is ErrServerClosed.

        func (*Server) SetKeepAlivesEnabled

        func (srv *Server) SetKeepAlivesEnabled(v bool)

        SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. By default, keep-alives are always enabled. Only very resource-constrained environments or servers in the process of shutting down should disable them.

        func (*Server) Shutdown

        func (srv *Server) Shutdown(ctx context.Context) error

        Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener(s).

        When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return ErrServerClosed. Make sure the program doesn't exit and waits instead for Shutdown to return.

        Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets. The caller of Shutdown should separately notify such long-lived connections of shutdown and wait for them to close, if desired. See Server.RegisterOnShutdown for a way to register shutdown notification functions.

        Once Shutdown has been called on a server, it may not be reused; future calls to methods such as Serve will return ErrServerClosed.

        Example

        Code:

        var srv http.Server
        
        idleConnsClosed := make(chan struct{})
        go func() {
            sigint := make(chan os.Signal, 1)
            signal.Notify(sigint, os.Interrupt)
            <-sigint
        
            // We received an interrupt signal, shut down.
            if err := srv.Shutdown(context.Background()); err != nil {
                // Error from closing listeners, or context timeout:
                log.Printf("HTTP server Shutdown: %v", err)
            }
            close(idleConnsClosed)
        }()
        
        if err := srv.ListenAndServe(); err != http.ErrServerClosed {
            // Error starting or closing listener:
            log.Fatalf("HTTP server ListenAndServe: %v", err)
        }
        
        <-idleConnsClosed
        

        type Transport

        Transport is an implementation of RoundTripper that supports HTTP, HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).

        By default, Transport caches connections for future re-use. This may leave many open connections when accessing many hosts. This behavior can be managed using Transport.CloseIdleConnections method and the [Transport.MaxIdleConnsPerHost] and [Transport.DisableKeepAlives] fields.

        Transports should be reused instead of created as needed. Transports are safe for concurrent use by multiple goroutines.

        A Transport is a low-level primitive for making HTTP and HTTPS requests. For high-level functionality, such as cookies and redirects, see Client.

        Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2 for HTTPS URLs, depending on whether the server supports HTTP/2, and how the Transport is configured. The DefaultTransport supports HTTP/2. To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2 and call ConfigureTransport. See the package docs for more about HTTP/2.

        Responses with status codes in the 1xx range are either handled automatically (100 expect-continue) or ignored. The one exception is HTTP status code 101 (Switching Protocols), which is considered a terminal status and returned by Transport.RoundTrip. To see the ignored 1xx responses, use the httptrace trace package's ClientTrace.Got1xxResponse.

        Transport only retries a request upon encountering a network error if the connection has been already been used successfully and if the request is idempotent and either has no body or has its [Request.GetBody] defined. HTTP requests are considered idempotent if they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or if their Header map contains an "Idempotency-Key" or "X-Idempotency-Key" entry. If the idempotency key value is a zero-length slice, the request is treated as idempotent but the header is not sent on the wire.

        type Transport struct {
        
            // Proxy specifies a function to return a proxy for a given
            // Request. If the function returns a non-nil error, the
            // request is aborted with the provided error.
            //
            // The proxy type is determined by the URL scheme. "http",
            // "https", and "socks5" are supported. If the scheme is empty,
            // "http" is assumed.
            //
            // If the proxy URL contains a userinfo subcomponent,
            // the proxy request will pass the username and password
            // in a Proxy-Authorization header.
            //
            // If Proxy is nil or returns a nil *URL, no proxy is used.
            Proxy func(*Request) (*url.URL, error)
        
            // OnProxyConnectResponse is called when the Transport gets an HTTP response from
            // a proxy for a CONNECT request. It's called before the check for a 200 OK response.
            // If it returns an error, the request fails with that error.
            OnProxyConnectResponse func(ctx context.Context, proxyURL *url.URL, connectReq *Request, connectRes *Response) error
        
            // DialContext specifies the dial function for creating unencrypted TCP connections.
            // If DialContext is nil (and the deprecated Dial below is also nil),
            // then the transport dials using package net.
            //
            // DialContext runs concurrently with calls to RoundTrip.
            // A RoundTrip call that initiates a dial may end up using
            // a connection dialed previously when the earlier connection
            // becomes idle before the later DialContext completes.
            DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
        
            // Dial specifies the dial function for creating unencrypted TCP connections.
            //
            // Dial runs concurrently with calls to RoundTrip.
            // A RoundTrip call that initiates a dial may end up using
            // a connection dialed previously when the earlier connection
            // becomes idle before the later Dial completes.
            //
            // Deprecated: Use DialContext instead, which allows the transport
            // to cancel dials as soon as they are no longer needed.
            // If both are set, DialContext takes priority.
            Dial func(network, addr string) (net.Conn, error)
        
            // DialTLSContext specifies an optional dial function for creating
            // TLS connections for non-proxied HTTPS requests.
            //
            // If DialTLSContext is nil (and the deprecated DialTLS below is also nil),
            // DialContext and TLSClientConfig are used.
            //
            // If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS
            // requests and the TLSClientConfig and TLSHandshakeTimeout
            // are ignored. The returned net.Conn is assumed to already be
            // past the TLS handshake.
            DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)
        
            // DialTLS specifies an optional dial function for creating
            // TLS connections for non-proxied HTTPS requests.
            //
            // Deprecated: Use DialTLSContext instead, which allows the transport
            // to cancel dials as soon as they are no longer needed.
            // If both are set, DialTLSContext takes priority.
            DialTLS func(network, addr string) (net.Conn, error)
        
            // TLSClientConfig specifies the TLS configuration to use with
            // tls.Client.
            // If nil, the default configuration is used.
            // If non-nil, HTTP/2 support may not be enabled by default.
            TLSClientConfig *tls.Config
        
            // TLSHandshakeTimeout specifies the maximum amount of time to
            // wait for a TLS handshake. Zero means no timeout.
            TLSHandshakeTimeout time.Duration
        
            // DisableKeepAlives, if true, disables HTTP keep-alives and
            // will only use the connection to the server for a single
            // HTTP request.
            //
            // This is unrelated to the similarly named TCP keep-alives.
            DisableKeepAlives bool
        
            // DisableCompression, if true, prevents the Transport from
            // requesting compression with an "Accept-Encoding: gzip"
            // request header when the Request contains no existing
            // Accept-Encoding value. If the Transport requests gzip on
            // its own and gets a gzipped response, it's transparently
            // decoded in the Response.Body. However, if the user
            // explicitly requested gzip it is not automatically
            // uncompressed.
            DisableCompression bool
        
            // MaxIdleConns controls the maximum number of idle (keep-alive)
            // connections across all hosts. Zero means no limit.
            MaxIdleConns int
        
            // MaxIdleConnsPerHost, if non-zero, controls the maximum idle
            // (keep-alive) connections to keep per-host. If zero,
            // DefaultMaxIdleConnsPerHost is used.
            MaxIdleConnsPerHost int
        
            // MaxConnsPerHost optionally limits the total number of
            // connections per host, including connections in the dialing,
            // active, and idle states. On limit violation, dials will block.
            //
            // Zero means no limit.
            MaxConnsPerHost int
        
            // IdleConnTimeout is the maximum amount of time an idle
            // (keep-alive) connection will remain idle before closing
            // itself.
            // Zero means no limit.
            IdleConnTimeout time.Duration
        
            // ResponseHeaderTimeout, if non-zero, specifies the amount of
            // time to wait for a server's response headers after fully
            // writing the request (including its body, if any). This
            // time does not include the time to read the response body.
            ResponseHeaderTimeout time.Duration
        
            // ExpectContinueTimeout, if non-zero, specifies the amount of
            // time to wait for a server's first response headers after fully
            // writing the request headers if the request has an
            // "Expect: 100-continue" header. Zero means no timeout and
            // causes the body to be sent immediately, without
            // waiting for the server to approve.
            // This time does not include the time to send the request header.
            ExpectContinueTimeout time.Duration
        
            // TLSNextProto specifies how the Transport switches to an
            // alternate protocol (such as HTTP/2) after a TLS ALPN
            // protocol negotiation. If Transport dials a TLS connection
            // with a non-empty protocol name and TLSNextProto contains a
            // map entry for that key (such as "h2"), then the func is
            // called with the request's authority (such as "example.com"
            // or "example.com:1234") and the TLS connection. The function
            // must return a RoundTripper that then handles the request.
            // If TLSNextProto is not nil, HTTP/2 support is not enabled
            // automatically.
            TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper
        
            // ProxyConnectHeader optionally specifies headers to send to
            // proxies during CONNECT requests.
            // To set the header dynamically, see GetProxyConnectHeader.
            ProxyConnectHeader Header
        
            // GetProxyConnectHeader optionally specifies a func to return
            // headers to send to proxyURL during a CONNECT request to the
            // ip:port target.
            // If it returns an error, the Transport's RoundTrip fails with
            // that error. It can return (nil, nil) to not add headers.
            // If GetProxyConnectHeader is non-nil, ProxyConnectHeader is
            // ignored.
            GetProxyConnectHeader func(ctx context.Context, proxyURL *url.URL, target string) (Header, error)
        
            // MaxResponseHeaderBytes specifies a limit on how many
            // response bytes are allowed in the server's response
            // header.
            //
            // Zero means to use a default limit.
            MaxResponseHeaderBytes int64
        
            // WriteBufferSize specifies the size of the write buffer used
            // when writing to the transport.
            // If zero, a default (currently 4KB) is used.
            WriteBufferSize int
        
            // ReadBufferSize specifies the size of the read buffer used
            // when reading from the transport.
            // If zero, a default (currently 4KB) is used.
            ReadBufferSize int
        
            // ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero
            // Dial, DialTLS, or DialContext func or TLSClientConfig is provided.
            // By default, use of any those fields conservatively disables HTTP/2.
            // To use a custom dialer or TLS config and still attempt HTTP/2
            // upgrades, set this to true.
            ForceAttemptHTTP2 bool
            // contains filtered or unexported fields
        }
        

        func (*Transport) CancelRequest

        func (t *Transport) CancelRequest(req *Request)

        CancelRequest cancels an in-flight request by closing its connection. CancelRequest should only be called after Transport.RoundTrip has returned.

        Deprecated: Use Request.WithContext to create a request with a cancelable context instead. CancelRequest cannot cancel HTTP/2 requests.

        func (*Transport) Clone

        func (t *Transport) Clone() *Transport

        Clone returns a deep copy of t's exported fields.

        func (*Transport) CloseIdleConnections

        func (t *Transport) CloseIdleConnections()

        CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.

        func (*Transport) RegisterProtocol

        func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)

        RegisterProtocol registers a new protocol with scheme. The Transport will pass requests using the given scheme to rt. It is rt's responsibility to simulate HTTP request semantics.

        RegisterProtocol can be used by other packages to provide implementations of protocol schemes like "ftp" or "file".

        If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will handle the Transport.RoundTrip itself for that one request, as if the protocol were not registered.

        func (*Transport) RoundTrip

        func (t *Transport) RoundTrip(req *Request) (*Response, error)

        RoundTrip implements the RoundTripper interface.

        For higher-level HTTP client support (such as handling of cookies and redirects), see Get, Post, and the Client type.

        Like the RoundTripper interface, the error types returned by RoundTrip are unspecified.

        Subdirectories

        Name Synopsis
        ..
        cgi Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.
        cookiejar Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
        fcgi Package fcgi implements the FastCGI protocol.
        httptest Package httptest provides utilities for HTTP testing.
        httptrace Package httptrace provides mechanisms to trace the events within HTTP client requests.
        httputil Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package.
        pprof Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
        cgi - Go Documentation Server
        ...

        Package cgi

        import "net/http/cgi"
        Overview
        Index

        Overview ▾

        Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.

        Note that using CGI means starting a new process to handle each request, which is typically less efficient than using a long-running server. This package is intended primarily for compatibility with existing systems.

        func Request

        func Request() (*http.Request, error)

        Request returns the HTTP request as represented in the current environment. This assumes the current program is being run by a web server in a CGI environment. The returned Request's Body is populated, if applicable.

        func RequestFromMap

        func RequestFromMap(params map[string]string) (*http.Request, error)

        RequestFromMap creates an http.Request from CGI variables. The returned Request's Body field is not populated.

        func Serve

        func Serve(handler http.Handler) error

        Serve executes the provided Handler on the currently active CGI request, if any. If there's no current CGI environment an error is returned. The provided handler may be nil to use http.DefaultServeMux.

        type Handler

        Handler runs an executable in a subprocess with a CGI environment.

        type Handler struct {
            Path string // path to the CGI executable
            Root string // root URI prefix of handler or empty for "/"
        
            // Dir specifies the CGI executable's working directory.
            // If Dir is empty, the base directory of Path is used.
            // If Path has no base directory, the current working
            // directory is used.
            Dir string
        
            Env        []string    // extra environment variables to set, if any, as "key=value"
            InheritEnv []string    // environment variables to inherit from host, as "key"
            Logger     *log.Logger // optional log for errors or nil to use log.Print
            Args       []string    // optional arguments to pass to child process
            Stderr     io.Writer   // optional stderr for the child process; nil means os.Stderr
        
            // PathLocationHandler specifies the root http Handler that
            // should handle internal redirects when the CGI process
            // returns a Location header value starting with a "/", as
            // specified in RFC 3875 § 6.3.2. This will likely be
            // http.DefaultServeMux.
            //
            // If nil, a CGI response with a local URI path is instead sent
            // back to the client and not redirected internally.
            PathLocationHandler http.Handler
        }
        

        func (*Handler) ServeHTTP

        func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request)
        cookiejar - Go Documentation Server
        ...

        Package cookiejar

        import "net/http/cookiejar"
        Overview
        Index
        Examples

        Overview ▾

        Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.

        type Jar

        Jar implements the http.CookieJar interface from the net/http package.

        type Jar struct {
            // contains filtered or unexported fields
        }
        

        func New

        func New(o *Options) (*Jar, error)

        New returns a new cookie jar. A nil *Options is equivalent to a zero Options.

        Example

        Code:

        // Start a server to give us cookies.
        ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            if cookie, err := r.Cookie("Flavor"); err != nil {
                http.SetCookie(w, &http.Cookie{Name: "Flavor", Value: "Chocolate Chip"})
            } else {
                cookie.Value = "Oatmeal Raisin"
                http.SetCookie(w, cookie)
            }
        }))
        defer ts.Close()
        
        u, err := url.Parse(ts.URL)
        if err != nil {
            log.Fatal(err)
        }
        
        // All users of cookiejar should import "golang.org/x/net/publicsuffix"
        jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
        if err != nil {
            log.Fatal(err)
        }
        
        client := &http.Client{
            Jar: jar,
        }
        
        if _, err = client.Get(u.String()); err != nil {
            log.Fatal(err)
        }
        
        fmt.Println("After 1st request:")
        for _, cookie := range jar.Cookies(u) {
            fmt.Printf("  %s: %s\n", cookie.Name, cookie.Value)
        }
        
        if _, err = client.Get(u.String()); err != nil {
            log.Fatal(err)
        }
        
        fmt.Println("After 2nd request:")
        for _, cookie := range jar.Cookies(u) {
            fmt.Printf("  %s: %s\n", cookie.Name, cookie.Value)
        }
        

        Output:

        After 1st request:
          Flavor: Chocolate Chip
        After 2nd request:
          Flavor: Oatmeal Raisin
        

        func (*Jar) Cookies

        func (j *Jar) Cookies(u *url.URL) (cookies []*http.Cookie)

        Cookies implements the Cookies method of the http.CookieJar interface.

        It returns an empty slice if the URL's scheme is not HTTP or HTTPS.

        func (*Jar) SetCookies

        func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie)

        SetCookies implements the SetCookies method of the http.CookieJar interface.

        It does nothing if the URL's scheme is not HTTP or HTTPS.

        type Options

        Options are the options for creating a new Jar.

        type Options struct {
            // PublicSuffixList is the public suffix list that determines whether
            // an HTTP server can set a cookie for a domain.
            //
            // A nil value is valid and may be useful for testing but it is not
            // secure: it means that the HTTP server for foo.co.uk can set a cookie
            // for bar.co.uk.
            PublicSuffixList PublicSuffixList
        }
        

        type PublicSuffixList

        PublicSuffixList provides the public suffix of a domain. For example:

        • the public suffix of "example.com" is "com",
        • the public suffix of "foo1.foo2.foo3.co.uk" is "co.uk", and
        • the public suffix of "bar.pvt.k12.ma.us" is "pvt.k12.ma.us".

        Implementations of PublicSuffixList must be safe for concurrent use by multiple goroutines.

        An implementation that always returns "" is valid and may be useful for testing but it is not secure: it means that the HTTP server for foo.com can set a cookie for bar.com.

        A public suffix list implementation is in the package golang.org/x/net/publicsuffix.

        type PublicSuffixList interface {
            // PublicSuffix returns the public suffix of domain.
            //
            // TODO: specify which of the caller and callee is responsible for IP
            // addresses, for leading and trailing dots, for case sensitivity, and
            // for IDN/Punycode.
            PublicSuffix(domain string) string
        
            // String returns a description of the source of this public suffix
            // list. The description will typically contain something like a time
            // stamp or version number.
            String() string
        }
        fcgi - Go Documentation Server
        ...

        Package fcgi

        import "net/http/fcgi"
        Overview
        Index

        Overview ▾

        Package fcgi implements the FastCGI protocol.

        See https://fast-cgi.github.io/ for an unofficial mirror of the original documentation.

        Currently only the responder role is supported.

        Variables

        ErrConnClosed is returned by Read when a handler attempts to read the body of a request after the connection to the web server has been closed.

        var ErrConnClosed = errors.New("fcgi: connection to web server closed")

        ErrRequestAborted is returned by Read when a handler attempts to read the body of a request that has been aborted by the web server.

        var ErrRequestAborted = errors.New("fcgi: request aborted by web server")

        func ProcessEnv

        func ProcessEnv(r *http.Request) map[string]string

        ProcessEnv returns FastCGI environment variables associated with the request r for which no effort was made to be included in the request itself - the data is hidden in the request's context. As an example, if REMOTE_USER is set for a request, it will not be found anywhere in r, but it will be included in ProcessEnv's response (via r's context).

        func Serve

        func Serve(l net.Listener, handler http.Handler) error

        Serve accepts incoming FastCGI connections on the listener l, creating a new goroutine for each. The goroutine reads requests and then calls handler to reply to them. If l is nil, Serve accepts connections from os.Stdin. If handler is nil, http.DefaultServeMux is used.

        httptest - Go Documentation Server
        ...

        Package httptest

        import "net/http/httptest"
        Overview
        Index
        Examples

        Overview ▾

        Package httptest provides utilities for HTTP testing.

        Constants

        DefaultRemoteAddr is the default remote address to return in RemoteAddr if an explicit DefaultRemoteAddr isn't set on ResponseRecorder.

        const DefaultRemoteAddr = "1.2.3.4"

        func NewRequest

        func NewRequest(method, target string, body io.Reader) *http.Request

        NewRequest returns a new incoming server Request, suitable for passing to an http.Handler for testing.

        The target is the RFC 7230 "request-target": it may be either a path or an absolute URL. If target is an absolute URL, the host name from the URL is used. Otherwise, "example.com" is used.

        The TLS field is set to a non-nil dummy value if target has scheme "https".

        The Request.Proto is always HTTP/1.1.

        An empty method means "GET".

        The provided body may be nil. If the body is of type *bytes.Reader, *strings.Reader, or *bytes.Buffer, the Request.ContentLength is set.

        NewRequest panics on error for ease of use in testing, where a panic is acceptable.

        To generate a client HTTP request instead of a server request, see the NewRequest function in the net/http package.

        type ResponseRecorder

        ResponseRecorder is an implementation of http.ResponseWriter that records its mutations for later inspection in tests.

        type ResponseRecorder struct {
            // Code is the HTTP response code set by WriteHeader.
            //
            // Note that if a Handler never calls WriteHeader or Write,
            // this might end up being 0, rather than the implicit
            // http.StatusOK. To get the implicit value, use the Result
            // method.
            Code int
        
            // HeaderMap contains the headers explicitly set by the Handler.
            // It is an internal detail.
            //
            // Deprecated: HeaderMap exists for historical compatibility
            // and should not be used. To access the headers returned by a handler,
            // use the Response.Header map as returned by the Result method.
            HeaderMap http.Header
        
            // Body is the buffer to which the Handler's Write calls are sent.
            // If nil, the Writes are silently discarded.
            Body *bytes.Buffer
        
            // Flushed is whether the Handler called Flush.
            Flushed bool
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        handler := func(w http.ResponseWriter, r *http.Request) {
            io.WriteString(w, "<html><body>Hello World!</body></html>")
        }
        
        req := httptest.NewRequest("GET", "http://example.com/foo", nil)
        w := httptest.NewRecorder()
        handler(w, req)
        
        resp := w.Result()
        body, _ := io.ReadAll(resp.Body)
        
        fmt.Println(resp.StatusCode)
        fmt.Println(resp.Header.Get("Content-Type"))
        fmt.Println(string(body))
        
        

        Output:

        200
        text/html; charset=utf-8
        <html><body>Hello World!</body></html>
        

        func NewRecorder

        func NewRecorder() *ResponseRecorder

        NewRecorder returns an initialized ResponseRecorder.

        func (*ResponseRecorder) Flush

        func (rw *ResponseRecorder) Flush()

        Flush implements http.Flusher. To test whether Flush was called, see rw.Flushed.

        func (*ResponseRecorder) Header

        func (rw *ResponseRecorder) Header() http.Header

        Header implements http.ResponseWriter. It returns the response headers to mutate within a handler. To test the headers that were written after a handler completes, use the ResponseRecorder.Result method and see the returned Response value's Header.

        func (*ResponseRecorder) Result

        func (rw *ResponseRecorder) Result() *http.Response

        Result returns the response generated by the handler.

        The returned Response will have at least its StatusCode, Header, Body, and optionally Trailer populated. More fields may be populated in the future, so callers should not DeepEqual the result in tests.

        The Response.Header is a snapshot of the headers at the time of the first write call, or at the time of this call, if the handler never did a write.

        The Response.Body is guaranteed to be non-nil and Body.Read call is guaranteed to not return any error other than io.EOF.

        Result must only be called after the handler has finished running.

        func (*ResponseRecorder) Write

        func (rw *ResponseRecorder) Write(buf []byte) (int, error)

        Write implements http.ResponseWriter. The data in buf is written to rw.Body, if not nil.

        func (*ResponseRecorder) WriteHeader

        func (rw *ResponseRecorder) WriteHeader(code int)

        WriteHeader implements http.ResponseWriter.

        func (*ResponseRecorder) WriteString

        func (rw *ResponseRecorder) WriteString(str string) (int, error)

        WriteString implements io.StringWriter. The data in str is written to rw.Body, if not nil.

        type Server

        A Server is an HTTP server listening on a system-chosen port on the local loopback interface, for use in end-to-end HTTP tests.

        type Server struct {
            URL      string // base URL of form http://ipaddr:port with no trailing slash
            Listener net.Listener
        
            // EnableHTTP2 controls whether HTTP/2 is enabled
            // on the server. It must be set between calling
            // NewUnstartedServer and calling Server.StartTLS.
            EnableHTTP2 bool
        
            // TLS is the optional TLS configuration, populated with a new config
            // after TLS is started. If set on an unstarted server before StartTLS
            // is called, existing fields are copied into the new config.
            TLS *tls.Config
        
            // Config may be changed after calling NewUnstartedServer and
            // before Start or StartTLS.
            Config *http.Server
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintln(w, "Hello, client")
        }))
        defer ts.Close()
        
        res, err := http.Get(ts.URL)
        if err != nil {
            log.Fatal(err)
        }
        greeting, err := io.ReadAll(res.Body)
        res.Body.Close()
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%s", greeting)
        

        Output:

        Hello, client
        

        Example (HTTP2)

        Code:

        ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintf(w, "Hello, %s", r.Proto)
        }))
        ts.EnableHTTP2 = true
        ts.StartTLS()
        defer ts.Close()
        
        res, err := ts.Client().Get(ts.URL)
        if err != nil {
            log.Fatal(err)
        }
        greeting, err := io.ReadAll(res.Body)
        res.Body.Close()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s", greeting)
        
        

        Output:

        Hello, HTTP/2.0
        

        func NewServer

        func NewServer(handler http.Handler) *Server

        NewServer starts and returns a new Server. The caller should call Close when finished, to shut it down.

        func NewTLSServer

        func NewTLSServer(handler http.Handler) *Server

        NewTLSServer starts and returns a new Server using TLS. The caller should call Close when finished, to shut it down.

        Example

        Code:

        ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintln(w, "Hello, client")
        }))
        defer ts.Close()
        
        client := ts.Client()
        res, err := client.Get(ts.URL)
        if err != nil {
            log.Fatal(err)
        }
        
        greeting, err := io.ReadAll(res.Body)
        res.Body.Close()
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%s", greeting)
        

        Output:

        Hello, client
        

        func NewUnstartedServer

        func NewUnstartedServer(handler http.Handler) *Server

        NewUnstartedServer returns a new Server but doesn't start it.

        After changing its configuration, the caller should call Start or StartTLS.

        The caller should call Close when finished, to shut it down.

        func (*Server) Certificate

        func (s *Server) Certificate() *x509.Certificate

        Certificate returns the certificate used by the server, or nil if the server doesn't use TLS.

        func (*Server) Client

        func (s *Server) Client() *http.Client

        Client returns an HTTP client configured for making requests to the server. It is configured to trust the server's TLS test certificate and will close its idle connections on Server.Close.

        func (*Server) Close

        func (s *Server) Close()

        Close shuts down the server and blocks until all outstanding requests on this server have completed.

        func (*Server) CloseClientConnections

        func (s *Server) CloseClientConnections()

        CloseClientConnections closes any open HTTP connections to the test Server.

        func (*Server) Start

        func (s *Server) Start()

        Start starts a server from NewUnstartedServer.

        func (*Server) StartTLS

        func (s *Server) StartTLS()

        StartTLS starts TLS on a server from NewUnstartedServer.

        httptrace - Go Documentation Server
        ...

        Package httptrace

        import "net/http/httptrace"
        Overview
        Index
        Examples

        Overview ▾

        Package httptrace provides mechanisms to trace the events within HTTP client requests.

        Example

        Code:

        req, _ := http.NewRequest("GET", "http://example.com", nil)
        trace := &httptrace.ClientTrace{
            GotConn: func(connInfo httptrace.GotConnInfo) {
                fmt.Printf("Got Conn: %+v\n", connInfo)
            },
            DNSDone: func(dnsInfo httptrace.DNSDoneInfo) {
                fmt.Printf("DNS Info: %+v\n", dnsInfo)
            },
        }
        req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
        _, err := http.DefaultTransport.RoundTrip(req)
        if err != nil {
            log.Fatal(err)
        }
        

        func WithClientTrace

        func WithClientTrace(ctx context.Context, trace *ClientTrace) context.Context

        WithClientTrace returns a new context based on the provided parent ctx. HTTP client requests made with the returned context will use the provided trace hooks, in addition to any previous hooks registered with ctx. Any hooks defined in the provided trace will be called first.

        type ClientTrace

        ClientTrace is a set of hooks to run at various stages of an outgoing HTTP request. Any particular hook may be nil. Functions may be called concurrently from different goroutines and some may be called after the request has completed or failed.

        ClientTrace currently traces a single HTTP request & response during a single round trip and has no hooks that span a series of redirected requests.

        See https://blog.golang.org/http-tracing for more.

        type ClientTrace struct {
            // GetConn is called before a connection is created or
            // retrieved from an idle pool. The hostPort is the
            // "host:port" of the target or proxy. GetConn is called even
            // if there's already an idle cached connection available.
            GetConn func(hostPort string)
        
            // GotConn is called after a successful connection is
            // obtained. There is no hook for failure to obtain a
            // connection; instead, use the error from
            // Transport.RoundTrip.
            GotConn func(GotConnInfo)
        
            // PutIdleConn is called when the connection is returned to
            // the idle pool. If err is nil, the connection was
            // successfully returned to the idle pool. If err is non-nil,
            // it describes why not. PutIdleConn is not called if
            // connection reuse is disabled via Transport.DisableKeepAlives.
            // PutIdleConn is called before the caller's Response.Body.Close
            // call returns.
            // For HTTP/2, this hook is not currently used.
            PutIdleConn func(err error)
        
            // GotFirstResponseByte is called when the first byte of the response
            // headers is available.
            GotFirstResponseByte func()
        
            // Got100Continue is called if the server replies with a "100
            // Continue" response.
            Got100Continue func()
        
            // Got1xxResponse is called for each 1xx informational response header
            // returned before the final non-1xx response. Got1xxResponse is called
            // for "100 Continue" responses, even if Got100Continue is also defined.
            // If it returns an error, the client request is aborted with that error value.
            Got1xxResponse func(code int, header textproto.MIMEHeader) error
        
            // DNSStart is called when a DNS lookup begins.
            DNSStart func(DNSStartInfo)
        
            // DNSDone is called when a DNS lookup ends.
            DNSDone func(DNSDoneInfo)
        
            // ConnectStart is called when a new connection's Dial begins.
            // If net.Dialer.DualStack (IPv6 "Happy Eyeballs") support is
            // enabled, this may be called multiple times.
            ConnectStart func(network, addr string)
        
            // ConnectDone is called when a new connection's Dial
            // completes. The provided err indicates whether the
            // connection completed successfully.
            // If net.Dialer.DualStack ("Happy Eyeballs") support is
            // enabled, this may be called multiple times.
            ConnectDone func(network, addr string, err error)
        
            // TLSHandshakeStart is called when the TLS handshake is started. When
            // connecting to an HTTPS site via an HTTP proxy, the handshake happens
            // after the CONNECT request is processed by the proxy.
            TLSHandshakeStart func()
        
            // TLSHandshakeDone is called after the TLS handshake with either the
            // successful handshake's connection state, or a non-nil error on handshake
            // failure.
            TLSHandshakeDone func(tls.ConnectionState, error)
        
            // WroteHeaderField is called after the Transport has written
            // each request header. At the time of this call the values
            // might be buffered and not yet written to the network.
            WroteHeaderField func(key string, value []string)
        
            // WroteHeaders is called after the Transport has written
            // all request headers.
            WroteHeaders func()
        
            // Wait100Continue is called if the Request specified
            // "Expect: 100-continue" and the Transport has written the
            // request headers but is waiting for "100 Continue" from the
            // server before writing the request body.
            Wait100Continue func()
        
            // WroteRequest is called with the result of writing the
            // request and any body. It may be called multiple times
            // in the case of retried requests.
            WroteRequest func(WroteRequestInfo)
        }
        

        func ContextClientTrace

        func ContextClientTrace(ctx context.Context) *ClientTrace

        ContextClientTrace returns the ClientTrace associated with the provided context. If none, it returns nil.

        type DNSDoneInfo

        DNSDoneInfo contains information about the results of a DNS lookup.

        type DNSDoneInfo struct {
            // Addrs are the IPv4 and/or IPv6 addresses found in the DNS
            // lookup. The contents of the slice should not be mutated.
            Addrs []net.IPAddr
        
            // Err is any error that occurred during the DNS lookup.
            Err error
        
            // Coalesced is whether the Addrs were shared with another
            // caller who was doing the same DNS lookup concurrently.
            Coalesced bool
        }
        

        type DNSStartInfo

        DNSStartInfo contains information about a DNS request.

        type DNSStartInfo struct {
            Host string
        }
        

        type GotConnInfo

        GotConnInfo is the argument to the [ClientTrace.GotConn] function and contains information about the obtained connection.

        type GotConnInfo struct {
            // Conn is the connection that was obtained. It is owned by
            // the http.Transport and should not be read, written or
            // closed by users of ClientTrace.
            Conn net.Conn
        
            // Reused is whether this connection has been previously
            // used for another HTTP request.
            Reused bool
        
            // WasIdle is whether this connection was obtained from an
            // idle pool.
            WasIdle bool
        
            // IdleTime reports how long the connection was previously
            // idle, if WasIdle is true.
            IdleTime time.Duration
        }
        

        type WroteRequestInfo

        WroteRequestInfo contains information provided to the WroteRequest hook.

        type WroteRequestInfo struct {
            // Err is any error encountered while writing the Request.
            Err error
        }
        
        httputil - Go Documentation Server
        ...

        Package httputil

        import "net/http/httputil"
        Overview
        Index
        Examples

        Overview ▾

        Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package.

        Index ▾

        Package files

        dump.go httputil.go persist.go reverseproxy.go

        Variables

        var (
            // Deprecated: No longer used.
            ErrPersistEOF = &http.ProtocolError{ErrorString: "persistent connection closed"}
        
            // Deprecated: No longer used.
            ErrClosed = &http.ProtocolError{ErrorString: "connection closed by user"}
        
            // Deprecated: No longer used.
            ErrPipeline = &http.ProtocolError{ErrorString: "pipeline error"}
        )

        ErrLineTooLong is returned when reading malformed chunked data with lines that are too long.

        var ErrLineTooLong = internal.ErrLineTooLong

        func DumpRequest

        func DumpRequest(req *http.Request, body bool) ([]byte, error)

        DumpRequest returns the given request in its HTTP/1.x wire representation. It should only be used by servers to debug client requests. The returned representation is an approximation only; some details of the initial request are lost while parsing it into an http.Request. In particular, the order and case of header field names are lost. The order of values in multi-valued headers is kept intact. HTTP/2 requests are dumped in HTTP/1.x form, not in their original binary representations.

        If body is true, DumpRequest also returns the body. To do so, it consumes req.Body and then replaces it with a new io.ReadCloser that yields the same bytes. If DumpRequest returns an error, the state of req is undefined.

        The documentation for http.Request.Write details which fields of req are included in the dump.

        Example

        Code:

        ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            dump, err := httputil.DumpRequest(r, true)
            if err != nil {
                http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
                return
            }
        
            fmt.Fprintf(w, "%q", dump)
        }))
        defer ts.Close()
        
        const body = "Go is a general-purpose language designed with systems programming in mind."
        req, err := http.NewRequest("POST", ts.URL, strings.NewReader(body))
        if err != nil {
            log.Fatal(err)
        }
        req.Host = "www.example.org"
        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            log.Fatal(err)
        }
        defer resp.Body.Close()
        
        b, err := io.ReadAll(resp.Body)
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%s", b)
        
        

        Output:

        "POST / HTTP/1.1\r\nHost: www.example.org\r\nAccept-Encoding: gzip\r\nContent-Length: 75\r\nUser-Agent: Go-http-client/1.1\r\n\r\nGo is a general-purpose language designed with systems programming in mind."
        

        func DumpRequestOut

        func DumpRequestOut(req *http.Request, body bool) ([]byte, error)

        DumpRequestOut is like DumpRequest but for outgoing client requests. It includes any headers that the standard http.Transport adds, such as User-Agent.

        Example

        Code:

        const body = "Go is a general-purpose language designed with systems programming in mind."
        req, err := http.NewRequest("PUT", "http://www.example.org", strings.NewReader(body))
        if err != nil {
            log.Fatal(err)
        }
        
        dump, err := httputil.DumpRequestOut(req, true)
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%q", dump)
        
        

        Output:

        "PUT / HTTP/1.1\r\nHost: www.example.org\r\nUser-Agent: Go-http-client/1.1\r\nContent-Length: 75\r\nAccept-Encoding: gzip\r\n\r\nGo is a general-purpose language designed with systems programming in mind."
        

        func DumpResponse

        func DumpResponse(resp *http.Response, body bool) ([]byte, error)

        DumpResponse is like DumpRequest but dumps a response.

        Example

        Code:

        const body = "Go is a general-purpose language designed with systems programming in mind."
        ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            w.Header().Set("Date", "Wed, 19 Jul 1972 19:00:00 GMT")
            fmt.Fprintln(w, body)
        }))
        defer ts.Close()
        
        resp, err := http.Get(ts.URL)
        if err != nil {
            log.Fatal(err)
        }
        defer resp.Body.Close()
        
        dump, err := httputil.DumpResponse(resp, true)
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%q", dump)
        
        

        Output:

        "HTTP/1.1 200 OK\r\nContent-Length: 76\r\nContent-Type: text/plain; charset=utf-8\r\nDate: Wed, 19 Jul 1972 19:00:00 GMT\r\n\r\nGo is a general-purpose language designed with systems programming in mind.\n"
        

        func NewChunkedReader

        func NewChunkedReader(r io.Reader) io.Reader

        NewChunkedReader returns a new chunkedReader that translates the data read from r out of HTTP "chunked" format before returning it. The chunkedReader returns io.EOF when the final 0-length chunk is read.

        NewChunkedReader is not needed by normal applications. The http package automatically decodes chunking when reading response bodies.

        func NewChunkedWriter

        func NewChunkedWriter(w io.Writer) io.WriteCloser

        NewChunkedWriter returns a new chunkedWriter that translates writes into HTTP "chunked" format before writing them to w. Closing the returned chunkedWriter sends the final 0-length chunk that marks the end of the stream but does not send the final CRLF that appears after trailers; trailers and the last CRLF must be written separately.

        NewChunkedWriter is not needed by normal applications. The http package adds chunking automatically if handlers don't set a Content-Length header. Using NewChunkedWriter inside a handler would result in double chunking or chunking with a Content-Length length, both of which are wrong.

        type BufferPool

        A BufferPool is an interface for getting and returning temporary byte slices for use by io.CopyBuffer.

        type BufferPool interface {
            Get() []byte
            Put([]byte)
        }

        type ClientConn

        ClientConn is an artifact of Go's early HTTP implementation. It is low-level, old, and unused by Go's current HTTP stack. We should have deleted it before Go 1.

        Deprecated: Use Client or Transport in package net/http instead.

        type ClientConn struct {
            // contains filtered or unexported fields
        }
        

        func NewClientConn

        func NewClientConn(c net.Conn, r *bufio.Reader) *ClientConn

        NewClientConn is an artifact of Go's early HTTP implementation. It is low-level, old, and unused by Go's current HTTP stack. We should have deleted it before Go 1.

        Deprecated: Use the Client or Transport in package net/http instead.

        func NewProxyClientConn

        func NewProxyClientConn(c net.Conn, r *bufio.Reader) *ClientConn

        NewProxyClientConn is an artifact of Go's early HTTP implementation. It is low-level, old, and unused by Go's current HTTP stack. We should have deleted it before Go 1.

        Deprecated: Use the Client or Transport in package net/http instead.

        func (*ClientConn) Close

        func (cc *ClientConn) Close() error

        Close calls ClientConn.Hijack and then also closes the underlying connection.

        func (*ClientConn) Do

        func (cc *ClientConn) Do(req *http.Request) (*http.Response, error)

        Do is convenience method that writes a request and reads a response.

        func (*ClientConn) Hijack

        func (cc *ClientConn) Hijack() (c net.Conn, r *bufio.Reader)

        Hijack detaches the ClientConn and returns the underlying connection as well as the read-side bufio which may have some left over data. Hijack may be called before the user or Read have signaled the end of the keep-alive logic. The user should not call Hijack while ClientConn.Read or ClientConn.Write is in progress.

        func (*ClientConn) Pending

        func (cc *ClientConn) Pending() int

        Pending returns the number of unanswered requests that have been sent on the connection.

        func (*ClientConn) Read

        func (cc *ClientConn) Read(req *http.Request) (resp *http.Response, err error)

        Read reads the next response from the wire. A valid response might be returned together with an ErrPersistEOF, which means that the remote requested that this be the last request serviced. Read can be called concurrently with ClientConn.Write, but not with another Read.

        func (*ClientConn) Write

        func (cc *ClientConn) Write(req *http.Request) error

        Write writes a request. An ErrPersistEOF error is returned if the connection has been closed in an HTTP keep-alive sense. If req.Close equals true, the keep-alive connection is logically closed after this request and the opposing server is informed. An ErrUnexpectedEOF indicates the remote closed the underlying TCP connection, which is usually considered as graceful close.

        type ProxyRequest

        A ProxyRequest contains a request to be rewritten by a ReverseProxy.

        type ProxyRequest struct {
            // In is the request received by the proxy.
            // The Rewrite function must not modify In.
            In *http.Request
        
            // Out is the request which will be sent by the proxy.
            // The Rewrite function may modify or replace this request.
            // Hop-by-hop headers are removed from this request
            // before Rewrite is called.
            Out *http.Request
        }
        

        func (*ProxyRequest) SetURL

        func (r *ProxyRequest) SetURL(target *url.URL)

        SetURL routes the outbound request to the scheme, host, and base path provided in target. If the target's path is "/base" and the incoming request was for "/dir", the target request will be for "/base/dir".

        SetURL rewrites the outbound Host header to match the target's host. To preserve the inbound request's Host header (the default behavior of NewSingleHostReverseProxy):

        rewriteFunc := func(r *httputil.ProxyRequest) {
        	r.SetURL(url)
        	r.Out.Host = r.In.Host
        }
        

        func (*ProxyRequest) SetXForwarded

        func (r *ProxyRequest) SetXForwarded()

        SetXForwarded sets the X-Forwarded-For, X-Forwarded-Host, and X-Forwarded-Proto headers of the outbound request.

        • The X-Forwarded-For header is set to the client IP address.
        • The X-Forwarded-Host header is set to the host name requested by the client.
        • The X-Forwarded-Proto header is set to "http" or "https", depending on whether the inbound request was made on a TLS-enabled connection.

        If the outbound request contains an existing X-Forwarded-For header, SetXForwarded appends the client IP address to it. To append to the inbound request's X-Forwarded-For header (the default behavior of ReverseProxy when using a Director function), copy the header from the inbound request before calling SetXForwarded:

        rewriteFunc := func(r *httputil.ProxyRequest) {
        	r.Out.Header["X-Forwarded-For"] = r.In.Header["X-Forwarded-For"]
        	r.SetXForwarded()
        }
        

        type ReverseProxy

        ReverseProxy is an HTTP Handler that takes an incoming request and sends it to another server, proxying the response back to the client.

        1xx responses are forwarded to the client if the underlying transport supports ClientTrace.Got1xxResponse.

        type ReverseProxy struct {
            // Rewrite must be a function which modifies
            // the request into a new request to be sent
            // using Transport. Its response is then copied
            // back to the original client unmodified.
            // Rewrite must not access the provided ProxyRequest
            // or its contents after returning.
            //
            // The Forwarded, X-Forwarded, X-Forwarded-Host,
            // and X-Forwarded-Proto headers are removed from the
            // outbound request before Rewrite is called. See also
            // the ProxyRequest.SetXForwarded method.
            //
            // Unparsable query parameters are removed from the
            // outbound request before Rewrite is called.
            // The Rewrite function may copy the inbound URL's
            // RawQuery to the outbound URL to preserve the original
            // parameter string. Note that this can lead to security
            // issues if the proxy's interpretation of query parameters
            // does not match that of the downstream server.
            //
            // At most one of Rewrite or Director may be set.
            Rewrite func(*ProxyRequest)
        
            // Director is a function which modifies
            // the request into a new request to be sent
            // using Transport. Its response is then copied
            // back to the original client unmodified.
            // Director must not access the provided Request
            // after returning.
            //
            // By default, the X-Forwarded-For header is set to the
            // value of the client IP address. If an X-Forwarded-For
            // header already exists, the client IP is appended to the
            // existing values. As a special case, if the header
            // exists in the Request.Header map but has a nil value
            // (such as when set by the Director func), the X-Forwarded-For
            // header is not modified.
            //
            // To prevent IP spoofing, be sure to delete any pre-existing
            // X-Forwarded-For header coming from the client or
            // an untrusted proxy.
            //
            // Hop-by-hop headers are removed from the request after
            // Director returns, which can remove headers added by
            // Director. Use a Rewrite function instead to ensure
            // modifications to the request are preserved.
            //
            // Unparsable query parameters are removed from the outbound
            // request if Request.Form is set after Director returns.
            //
            // At most one of Rewrite or Director may be set.
            Director func(*http.Request)
        
            // The transport used to perform proxy requests.
            // If nil, http.DefaultTransport is used.
            Transport http.RoundTripper
        
            // FlushInterval specifies the flush interval
            // to flush to the client while copying the
            // response body.
            // If zero, no periodic flushing is done.
            // A negative value means to flush immediately
            // after each write to the client.
            // The FlushInterval is ignored when ReverseProxy
            // recognizes a response as a streaming response, or
            // if its ContentLength is -1; for such responses, writes
            // are flushed to the client immediately.
            FlushInterval time.Duration
        
            // ErrorLog specifies an optional logger for errors
            // that occur when attempting to proxy the request.
            // If nil, logging is done via the log package's standard logger.
            ErrorLog *log.Logger
        
            // BufferPool optionally specifies a buffer pool to
            // get byte slices for use by io.CopyBuffer when
            // copying HTTP response bodies.
            BufferPool BufferPool
        
            // ModifyResponse is an optional function that modifies the
            // Response from the backend. It is called if the backend
            // returns a response at all, with any HTTP status code.
            // If the backend is unreachable, the optional ErrorHandler is
            // called without any call to ModifyResponse.
            //
            // If ModifyResponse returns an error, ErrorHandler is called
            // with its error value. If ErrorHandler is nil, its default
            // implementation is used.
            ModifyResponse func(*http.Response) error
        
            // ErrorHandler is an optional function that handles errors
            // reaching the backend or errors from ModifyResponse.
            //
            // If nil, the default is to log the provided error and return
            // a 502 Status Bad Gateway response.
            ErrorHandler func(http.ResponseWriter, *http.Request, error)
        }
        

        Example

        Code:

        backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintln(w, "this call was relayed by the reverse proxy")
        }))
        defer backendServer.Close()
        
        rpURL, err := url.Parse(backendServer.URL)
        if err != nil {
            log.Fatal(err)
        }
        frontendProxy := httptest.NewServer(&httputil.ReverseProxy{
            Rewrite: func(r *httputil.ProxyRequest) {
                r.SetXForwarded()
                r.SetURL(rpURL)
            },
        })
        defer frontendProxy.Close()
        
        resp, err := http.Get(frontendProxy.URL)
        if err != nil {
            log.Fatal(err)
        }
        
        b, err := io.ReadAll(resp.Body)
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%s", b)
        
        

        Output:

        this call was relayed by the reverse proxy
        

        func NewSingleHostReverseProxy

        func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy

        NewSingleHostReverseProxy returns a new ReverseProxy that routes URLs to the scheme, host, and base path provided in target. If the target's path is "/base" and the incoming request was for "/dir", the target request will be for /base/dir.

        NewSingleHostReverseProxy does not rewrite the Host header.

        To customize the ReverseProxy behavior beyond what NewSingleHostReverseProxy provides, use ReverseProxy directly with a Rewrite function. The ProxyRequest SetURL method may be used to route the outbound request. (Note that SetURL, unlike NewSingleHostReverseProxy, rewrites the Host header of the outbound request by default.)

        proxy := &ReverseProxy{
        	Rewrite: func(r *ProxyRequest) {
        		r.SetURL(target)
        		r.Out.Host = r.In.Host // if desired
        	},
        }
        

        func (*ReverseProxy) ServeHTTP

        func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request)

        type ServerConn

        ServerConn is an artifact of Go's early HTTP implementation. It is low-level, old, and unused by Go's current HTTP stack. We should have deleted it before Go 1.

        Deprecated: Use the Server in package net/http instead.

        type ServerConn struct {
            // contains filtered or unexported fields
        }
        

        func NewServerConn

        func NewServerConn(c net.Conn, r *bufio.Reader) *ServerConn

        NewServerConn is an artifact of Go's early HTTP implementation. It is low-level, old, and unused by Go's current HTTP stack. We should have deleted it before Go 1.

        Deprecated: Use the Server in package net/http instead.

        func (*ServerConn) Close

        func (sc *ServerConn) Close() error

        Close calls ServerConn.Hijack and then also closes the underlying connection.

        func (*ServerConn) Hijack

        func (sc *ServerConn) Hijack() (net.Conn, *bufio.Reader)

        Hijack detaches the ServerConn and returns the underlying connection as well as the read-side bufio which may have some left over data. Hijack may be called before Read has signaled the end of the keep-alive logic. The user should not call Hijack while ServerConn.Read or ServerConn.Write is in progress.

        func (*ServerConn) Pending

        func (sc *ServerConn) Pending() int

        Pending returns the number of unanswered requests that have been received on the connection.

        func (*ServerConn) Read

        func (sc *ServerConn) Read() (*http.Request, error)

        Read returns the next request on the wire. An ErrPersistEOF is returned if it is gracefully determined that there are no more requests (e.g. after the first request on an HTTP/1.0 connection, or after a Connection:close on a HTTP/1.1 connection).

        func (*ServerConn) Write

        func (sc *ServerConn) Write(req *http.Request, resp *http.Response) error

        Write writes resp in response to req. To close the connection gracefully, set the Response.Close field to true. Write should be considered operational until it returns an error, regardless of any errors returned on the ServerConn.Read side.

        pprof - Go Documentation Server
        ...

        Package pprof

        import "net/http/pprof"
        Overview
        Index

        Overview ▾

        Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.

        The package is typically only imported for the side effect of registering its HTTP handlers. The handled paths all begin with /debug/pprof/.

        To use pprof, link this package into your program:

        import _ "net/http/pprof"
        

        If your application is not already running an http server, you need to start one. Add "net/http" and "log" to your imports and the following code to your main function:

        go func() {
        	log.Println(http.ListenAndServe("localhost:6060", nil))
        }()
        

        By default, all the profiles listed in runtime/pprof.Profile are available (via Handler), in addition to the Cmdline, Profile, Symbol, and Trace profiles defined in this package. If you are not using DefaultServeMux, you will have to register handlers with the mux you are using.

        Parameters

        Parameters can be passed via GET query params:

        • debug=N (all profiles): response format: N = 0: binary (default), N > 0: plaintext
        • gc=N (heap profile): N > 0: run a garbage collection cycle before profiling
        • seconds=N (allocs, block, goroutine, heap, mutex, threadcreate profiles): return a delta profile
        • seconds=N (cpu (profile), trace profiles): profile for the given duration

        Usage examples

        Use the pprof tool to look at the heap profile:

        go tool pprof http://localhost:6060/debug/pprof/heap
        

        Or to look at a 30-second CPU profile:

        go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
        

        Or to look at the goroutine blocking profile, after calling runtime.SetBlockProfileRate in your program:

        go tool pprof http://localhost:6060/debug/pprof/block
        

        Or to look at the holders of contended mutexes, after calling runtime.SetMutexProfileFraction in your program:

        go tool pprof http://localhost:6060/debug/pprof/mutex
        

        The package also exports a handler that serves execution trace data for the "go tool trace" command. To collect a 5-second execution trace:

        curl -o trace.out http://localhost:6060/debug/pprof/trace?seconds=5
        go tool trace trace.out
        

        To view all available profiles, open http://localhost:6060/debug/pprof/ in your browser.

        For a study of the facility in action, visit https://blog.golang.org/2011/06/profiling-go-programs.html.

        func Cmdline

        func Cmdline(w http.ResponseWriter, r *http.Request)

        Cmdline responds with the running program's command line, with arguments separated by NUL bytes. The package initialization registers it as /debug/pprof/cmdline.

        func Handler

        func Handler(name string) http.Handler

        Handler returns an HTTP handler that serves the named profile. Available profiles can be found in runtime/pprof.Profile.

        func Index

        func Index(w http.ResponseWriter, r *http.Request)

        Index responds with the pprof-formatted profile named by the request. For example, "/debug/pprof/heap" serves the "heap" profile. Index responds to a request for "/debug/pprof/" with an HTML page listing the available profiles.

        func Profile

        func Profile(w http.ResponseWriter, r *http.Request)

        Profile responds with the pprof-formatted cpu profile. Profiling lasts for duration specified in seconds GET parameter, or for 30 seconds if not specified. The package initialization registers it as /debug/pprof/profile.

        func Symbol

        func Symbol(w http.ResponseWriter, r *http.Request)

        Symbol looks up the program counters listed in the request, responding with a table mapping program counters to function names. The package initialization registers it as /debug/pprof/symbol.

        func Trace

        func Trace(w http.ResponseWriter, r *http.Request)

        Trace responds with the execution trace in binary form. Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified. The package initialization registers it as /debug/pprof/trace.

        mail - Go Documentation Server
        ...

        Package mail

        import "net/mail"
        Overview
        Index
        Examples

        Overview ▾

        Package mail implements parsing of mail messages.

        For the most part, this package follows the syntax as specified by RFC 5322 and extended by RFC 6532. Notable divergences:

        • Obsolete address formats are not parsed, including addresses with embedded route information.
        • The full range of spacing (the CFWS syntax element) is not supported, such as breaking addresses across lines.
        • No unicode normalization is performed.
        • The special characters ()[]:;@\, are allowed to appear unquoted in names.
        • A leading From line is permitted, as in mbox format (RFC 4155).

        Variables

        var ErrHeaderNotPresent = errors.New("mail: header not in message")

        func ParseDate

        func ParseDate(date string) (time.Time, error)

        ParseDate parses an RFC 5322 date string.

        type Address

        Address represents a single mail address. An address such as "Barry Gibbs <bg@example.com>" is represented as Address{Name: "Barry Gibbs", Address: "bg@example.com"}.

        type Address struct {
            Name    string // Proper name; may be empty.
            Address string // user@domain
        }
        

        func ParseAddress

        func ParseAddress(address string) (*Address, error)

        ParseAddress parses a single RFC 5322 address, e.g. "Barry Gibbs <bg@example.com>"

        Example

        Code:

        e, err := mail.ParseAddress("Alice <alice@example.com>")
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Println(e.Name, e.Address)
        
        

        Output:

        Alice alice@example.com
        

        func ParseAddressList

        func ParseAddressList(list string) ([]*Address, error)

        ParseAddressList parses the given string as a list of addresses.

        Example

        Code:

        const list = "Alice <alice@example.com>, Bob <bob@example.com>, Eve <eve@example.com>"
        emails, err := mail.ParseAddressList(list)
        if err != nil {
            log.Fatal(err)
        }
        
        for _, v := range emails {
            fmt.Println(v.Name, v.Address)
        }
        
        

        Output:

        Alice alice@example.com
        Bob bob@example.com
        Eve eve@example.com
        

        func (*Address) String

        func (a *Address) String() string

        String formats the address as a valid RFC 5322 address. If the address's name contains non-ASCII characters the name will be rendered according to RFC 2047.

        type AddressParser

        An AddressParser is an RFC 5322 address parser.

        type AddressParser struct {
            // WordDecoder optionally specifies a decoder for RFC 2047 encoded-words.
            WordDecoder *mime.WordDecoder
        }
        

        func (*AddressParser) Parse

        func (p *AddressParser) Parse(address string) (*Address, error)

        Parse parses a single RFC 5322 address of the form "Gogh Fir <gf@example.com>" or "foo@example.com".

        func (*AddressParser) ParseList

        func (p *AddressParser) ParseList(list string) ([]*Address, error)

        ParseList parses the given string as a list of comma-separated addresses of the form "Gogh Fir <gf@example.com>" or "foo@example.com".

        A Header represents the key-value pairs in a mail message header.

        type Header map[string][]string

        func (Header) AddressList

        func (h Header) AddressList(key string) ([]*Address, error)

        AddressList parses the named header field as a list of addresses.

        func (Header) Date

        func (h Header) Date() (time.Time, error)

        Date parses the Date header field.

        func (Header) Get

        func (h Header) Get(key string) string

        Get gets the first value associated with the given key. It is case insensitive; CanonicalMIMEHeaderKey is used to canonicalize the provided key. If there are no values associated with the key, Get returns "". To access multiple values of a key, or to use non-canonical keys, access the map directly.

        type Message

        A Message represents a parsed mail message.

        type Message struct {
            Header Header
            Body   io.Reader
        }
        

        func ReadMessage

        func ReadMessage(r io.Reader) (msg *Message, err error)

        ReadMessage reads a message from r. The headers are parsed, and the body of the message will be available for reading from msg.Body.

        Example

        Code:

        msg := `Date: Mon, 23 Jun 2015 11:40:36 -0400
        From: Gopher <from@example.com>
        To: Another Gopher <to@example.com>
        Subject: Gophers at Gophercon
        
        Message body
        `
        
        r := strings.NewReader(msg)
        m, err := mail.ReadMessage(r)
        if err != nil {
            log.Fatal(err)
        }
        
        header := m.Header
        fmt.Println("Date:", header.Get("Date"))
        fmt.Println("From:", header.Get("From"))
        fmt.Println("To:", header.Get("To"))
        fmt.Println("Subject:", header.Get("Subject"))
        
        body, err := io.ReadAll(m.Body)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s", body)
        
        

        Output:

        Date: Mon, 23 Jun 2015 11:40:36 -0400
        From: Gopher <from@example.com>
        To: Another Gopher <to@example.com>
        Subject: Gophers at Gophercon
        Message body
        
        netip - Go Documentation Server
        ...

        Package netip

        import "net/netip"
        Overview
        Index

        Overview ▾

        Package netip defines an IP address type that's a small value type. Building on that Addr type, the package also defines AddrPort (an IP address and a port) and Prefix (an IP address and a bit length prefix).

        Compared to the net.IP type, Addr type takes less memory, is immutable, and is comparable (supports == and being a map key).

        Index ▾

        type Addr
            func AddrFrom16(addr [16]byte) Addr
            func AddrFrom4(addr [4]byte) Addr
            func AddrFromSlice(slice []byte) (ip Addr, ok bool)
            func IPv4Unspecified() Addr
            func IPv6LinkLocalAllNodes() Addr
            func IPv6LinkLocalAllRouters() Addr
            func IPv6Loopback() Addr
            func IPv6Unspecified() Addr
            func MustParseAddr(s string) Addr
            func ParseAddr(s string) (Addr, error)
            func (ip Addr) AppendTo(b []byte) []byte
            func (ip Addr) As16() (a16 [16]byte)
            func (ip Addr) As4() (a4 [4]byte)
            func (ip Addr) AsSlice() []byte
            func (ip Addr) BitLen() int
            func (ip Addr) Compare(ip2 Addr) int
            func (ip Addr) Is4() bool
            func (ip Addr) Is4In6() bool
            func (ip Addr) Is6() bool
            func (ip Addr) IsGlobalUnicast() bool
            func (ip Addr) IsInterfaceLocalMulticast() bool
            func (ip Addr) IsLinkLocalMulticast() bool
            func (ip Addr) IsLinkLocalUnicast() bool
            func (ip Addr) IsLoopback() bool
            func (ip Addr) IsMulticast() bool
            func (ip Addr) IsPrivate() bool
            func (ip Addr) IsUnspecified() bool
            func (ip Addr) IsValid() bool
            func (ip Addr) Less(ip2 Addr) bool
            func (ip Addr) MarshalBinary() ([]byte, error)
            func (ip Addr) MarshalText() ([]byte, error)
            func (ip Addr) Next() Addr
            func (ip Addr) Prefix(b int) (Prefix, error)
            func (ip Addr) Prev() Addr
            func (ip Addr) String() string
            func (ip Addr) StringExpanded() string
            func (ip Addr) Unmap() Addr
            func (ip *Addr) UnmarshalBinary(b []byte) error
            func (ip *Addr) UnmarshalText(text []byte) error
            func (ip Addr) WithZone(zone string) Addr
            func (ip Addr) Zone() string
        type AddrPort
            func AddrPortFrom(ip Addr, port uint16) AddrPort
            func MustParseAddrPort(s string) AddrPort
            func ParseAddrPort(s string) (AddrPort, error)
            func (p AddrPort) Addr() Addr
            func (p AddrPort) AppendTo(b []byte) []byte
            func (p AddrPort) Compare(p2 AddrPort) int
            func (p AddrPort) IsValid() bool
            func (p AddrPort) MarshalBinary() ([]byte, error)
            func (p AddrPort) MarshalText() ([]byte, error)
            func (p AddrPort) Port() uint16
            func (p AddrPort) String() string
            func (p *AddrPort) UnmarshalBinary(b []byte) error
            func (p *AddrPort) UnmarshalText(text []byte) error
        type Prefix
            func MustParsePrefix(s string) Prefix
            func ParsePrefix(s string) (Prefix, error)
            func PrefixFrom(ip Addr, bits int) Prefix
            func (p Prefix) Addr() Addr
            func (p Prefix) AppendTo(b []byte) []byte
            func (p Prefix) Bits() int
            func (p Prefix) Contains(ip Addr) bool
            func (p Prefix) IsSingleIP() bool
            func (p Prefix) IsValid() bool
            func (p Prefix) MarshalBinary() ([]byte, error)
            func (p Prefix) MarshalText() ([]byte, error)
            func (p Prefix) Masked() Prefix
            func (p Prefix) Overlaps(o Prefix) bool
            func (p Prefix) String() string
            func (p *Prefix) UnmarshalBinary(b []byte) error
            func (p *Prefix) UnmarshalText(text []byte) error

        Package files

        leaf_alts.go netip.go uint128.go

        type Addr

        Addr represents an IPv4 or IPv6 address (with or without a scoped addressing zone), similar to net.IP or net.IPAddr.

        Unlike net.IP or net.IPAddr, Addr is a comparable value type (it supports == and can be a map key) and is immutable.

        The zero Addr is not a valid IP address. Addr{} is distinct from both 0.0.0.0 and ::.

        type Addr struct {
            // contains filtered or unexported fields
        }
        

        func AddrFrom16

        func AddrFrom16(addr [16]byte) Addr

        AddrFrom16 returns the IPv6 address given by the bytes in addr. An IPv4-mapped IPv6 address is left as an IPv6 address. (Use Unmap to convert them if needed.)

        func AddrFrom4

        func AddrFrom4(addr [4]byte) Addr

        AddrFrom4 returns the address of the IPv4 address given by the bytes in addr.

        func AddrFromSlice

        func AddrFromSlice(slice []byte) (ip Addr, ok bool)

        AddrFromSlice parses the 4- or 16-byte byte slice as an IPv4 or IPv6 address. Note that a net.IP can be passed directly as the []byte argument. If slice's length is not 4 or 16, AddrFromSlice returns Addr{}, false.

        func IPv4Unspecified

        func IPv4Unspecified() Addr

        IPv4Unspecified returns the IPv4 unspecified address "0.0.0.0".

        func IPv6LinkLocalAllNodes

        func IPv6LinkLocalAllNodes() Addr

        IPv6LinkLocalAllNodes returns the IPv6 link-local all nodes multicast address ff02::1.

        func IPv6LinkLocalAllRouters

        func IPv6LinkLocalAllRouters() Addr

        IPv6LinkLocalAllRouters returns the IPv6 link-local all routers multicast address ff02::2.

        func IPv6Loopback

        func IPv6Loopback() Addr

        IPv6Loopback returns the IPv6 loopback address ::1.

        func IPv6Unspecified

        func IPv6Unspecified() Addr

        IPv6Unspecified returns the IPv6 unspecified address "::".

        func MustParseAddr

        func MustParseAddr(s string) Addr

        MustParseAddr calls ParseAddr(s) and panics on error. It is intended for use in tests with hard-coded strings.

        func ParseAddr

        func ParseAddr(s string) (Addr, error)

        ParseAddr parses s as an IP address, returning the result. The string s can be in dotted decimal ("192.0.2.1"), IPv6 ("2001:db8::68"), or IPv6 with a scoped addressing zone ("fe80::1cc0:3e8c:119f:c2e1%ens18").

        func (Addr) AppendTo

        func (ip Addr) AppendTo(b []byte) []byte

        AppendTo appends a text encoding of ip, as generated by Addr.MarshalText, to b and returns the extended buffer.

        func (Addr) As16

        func (ip Addr) As16() (a16 [16]byte)

        As16 returns the IP address in its 16-byte representation. IPv4 addresses are returned as IPv4-mapped IPv6 addresses. IPv6 addresses with zones are returned without their zone (use the Addr.Zone method to get it). The ip zero value returns all zeroes.

        func (Addr) As4

        func (ip Addr) As4() (a4 [4]byte)

        As4 returns an IPv4 or IPv4-in-IPv6 address in its 4-byte representation. If ip is the zero Addr or an IPv6 address, As4 panics. Note that 0.0.0.0 is not the zero Addr.

        func (Addr) AsSlice

        func (ip Addr) AsSlice() []byte

        AsSlice returns an IPv4 or IPv6 address in its respective 4-byte or 16-byte representation.

        func (Addr) BitLen

        func (ip Addr) BitLen() int

        BitLen returns the number of bits in the IP address: 128 for IPv6, 32 for IPv4, and 0 for the zero Addr.

        Note that IPv4-mapped IPv6 addresses are considered IPv6 addresses and therefore have bit length 128.

        func (Addr) Compare

        func (ip Addr) Compare(ip2 Addr) int

        Compare returns an integer comparing two IPs. The result will be 0 if ip == ip2, -1 if ip < ip2, and +1 if ip > ip2. The definition of "less than" is the same as the Addr.Less method.

        func (Addr) Is4

        func (ip Addr) Is4() bool

        Is4 reports whether ip is an IPv4 address.

        It returns false for IPv4-mapped IPv6 addresses. See Addr.Unmap.

        func (Addr) Is4In6

        func (ip Addr) Is4In6() bool

        Is4In6 reports whether ip is an IPv4-mapped IPv6 address.

        func (Addr) Is6

        func (ip Addr) Is6() bool

        Is6 reports whether ip is an IPv6 address, including IPv4-mapped IPv6 addresses.

        func (Addr) IsGlobalUnicast

        func (ip Addr) IsGlobalUnicast() bool

        IsGlobalUnicast reports whether ip is a global unicast address.

        It returns true for IPv6 addresses which fall outside of the current IANA-allocated 2000::/3 global unicast space, with the exception of the link-local address space. It also returns true even if ip is in the IPv4 private address space or IPv6 unique local address space. It returns false for the zero Addr.

        For reference, see RFC 1122, RFC 4291, and RFC 4632.

        func (Addr) IsInterfaceLocalMulticast

        func (ip Addr) IsInterfaceLocalMulticast() bool

        IsInterfaceLocalMulticast reports whether ip is an IPv6 interface-local multicast address.

        func (Addr) IsLinkLocalMulticast

        func (ip Addr) IsLinkLocalMulticast() bool

        IsLinkLocalMulticast reports whether ip is a link-local multicast address.

        func (Addr) IsLinkLocalUnicast

        func (ip Addr) IsLinkLocalUnicast() bool

        IsLinkLocalUnicast reports whether ip is a link-local unicast address.

        func (Addr) IsLoopback

        func (ip Addr) IsLoopback() bool

        IsLoopback reports whether ip is a loopback address.

        func (Addr) IsMulticast

        func (ip Addr) IsMulticast() bool

        IsMulticast reports whether ip is a multicast address.

        func (Addr) IsPrivate

        func (ip Addr) IsPrivate() bool

        IsPrivate reports whether ip is a private address, according to RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses). That is, it reports whether ip is in 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, or fc00::/7. This is the same as net.IP.IsPrivate.

        func (Addr) IsUnspecified

        func (ip Addr) IsUnspecified() bool

        IsUnspecified reports whether ip is an unspecified address, either the IPv4 address "0.0.0.0" or the IPv6 address "::".

        Note that the zero Addr is not an unspecified address.

        func (Addr) IsValid

        func (ip Addr) IsValid() bool

        IsValid reports whether the Addr is an initialized address (not the zero Addr).

        Note that "0.0.0.0" and "::" are both valid values.

        func (Addr) Less

        func (ip Addr) Less(ip2 Addr) bool

        Less reports whether ip sorts before ip2. IP addresses sort first by length, then their address. IPv6 addresses with zones sort just after the same address without a zone.

        func (Addr) MarshalBinary

        func (ip Addr) MarshalBinary() ([]byte, error)

        MarshalBinary implements the encoding.BinaryMarshaler interface. It returns a zero-length slice for the zero Addr, the 4-byte form for an IPv4 address, and the 16-byte form with zone appended for an IPv6 address.

        func (Addr) MarshalText

        func (ip Addr) MarshalText() ([]byte, error)

        MarshalText implements the encoding.TextMarshaler interface, The encoding is the same as returned by Addr.String, with one exception: If ip is the zero Addr, the encoding is the empty string.

        func (Addr) Next

        func (ip Addr) Next() Addr

        Next returns the address following ip. If there is none, it returns the zero Addr.

        func (Addr) Prefix

        func (ip Addr) Prefix(b int) (Prefix, error)

        Prefix keeps only the top b bits of IP, producing a Prefix of the specified length. If ip is a zero Addr, Prefix always returns a zero Prefix and a nil error. Otherwise, if bits is less than zero or greater than ip.BitLen(), Prefix returns an error.

        func (Addr) Prev

        func (ip Addr) Prev() Addr

        Prev returns the IP before ip. If there is none, it returns the IP zero value.

        func (Addr) String

        func (ip Addr) String() string

        String returns the string form of the IP address ip. It returns one of 5 forms:

        • "invalid IP", if ip is the zero Addr
        • IPv4 dotted decimal ("192.0.2.1")
        • IPv6 ("2001:db8::1")
        • "::ffff:1.2.3.4" (if Addr.Is4In6)
        • IPv6 with zone ("fe80:db8::1%eth0")

        Note that unlike package net's IP.String method, IPv4-mapped IPv6 addresses format with a "::ffff:" prefix before the dotted quad.

        func (Addr) StringExpanded

        func (ip Addr) StringExpanded() string

        StringExpanded is like Addr.String but IPv6 addresses are expanded with leading zeroes and no "::" compression. For example, "2001:db8::1" becomes "2001:0db8:0000:0000:0000:0000:0000:0001".

        func (Addr) Unmap

        func (ip Addr) Unmap() Addr

        Unmap returns ip with any IPv4-mapped IPv6 address prefix removed.

        That is, if ip is an IPv6 address wrapping an IPv4 address, it returns the wrapped IPv4 address. Otherwise it returns ip unmodified.

        func (*Addr) UnmarshalBinary

        func (ip *Addr) UnmarshalBinary(b []byte) error

        UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. It expects data in the form generated by MarshalBinary.

        func (*Addr) UnmarshalText

        func (ip *Addr) UnmarshalText(text []byte) error

        UnmarshalText implements the encoding.TextUnmarshaler interface. The IP address is expected in a form accepted by ParseAddr.

        If text is empty, UnmarshalText sets *ip to the zero Addr and returns no error.

        func (Addr) WithZone

        func (ip Addr) WithZone(zone string) Addr

        WithZone returns an IP that's the same as ip but with the provided zone. If zone is empty, the zone is removed. If ip is an IPv4 address, WithZone is a no-op and returns ip unchanged.

        func (Addr) Zone

        func (ip Addr) Zone() string

        Zone returns ip's IPv6 scoped addressing zone, if any.

        type AddrPort

        AddrPort is an IP and a port number.

        type AddrPort struct {
            // contains filtered or unexported fields
        }
        

        func AddrPortFrom

        func AddrPortFrom(ip Addr, port uint16) AddrPort

        AddrPortFrom returns an AddrPort with the provided IP and port. It does not allocate.

        func MustParseAddrPort

        func MustParseAddrPort(s string) AddrPort

        MustParseAddrPort calls ParseAddrPort(s) and panics on error. It is intended for use in tests with hard-coded strings.

        func ParseAddrPort

        func ParseAddrPort(s string) (AddrPort, error)

        ParseAddrPort parses s as an AddrPort.

        It doesn't do any name resolution: both the address and the port must be numeric.

        func (AddrPort) Addr

        func (p AddrPort) Addr() Addr

        Addr returns p's IP address.

        func (AddrPort) AppendTo

        func (p AddrPort) AppendTo(b []byte) []byte

        AppendTo appends a text encoding of p, as generated by AddrPort.MarshalText, to b and returns the extended buffer.

        func (AddrPort) Compare

        func (p AddrPort) Compare(p2 AddrPort) int

        Compare returns an integer comparing two AddrPorts. The result will be 0 if p == p2, -1 if p < p2, and +1 if p > p2. AddrPorts sort first by IP address, then port.

        func (AddrPort) IsValid

        func (p AddrPort) IsValid() bool

        IsValid reports whether p.Addr() is valid. All ports are valid, including zero.

        func (AddrPort) MarshalBinary

        func (p AddrPort) MarshalBinary() ([]byte, error)

        MarshalBinary implements the encoding.BinaryMarshaler interface. It returns Addr.MarshalBinary with an additional two bytes appended containing the port in little-endian.

        func (AddrPort) MarshalText

        func (p AddrPort) MarshalText() ([]byte, error)

        MarshalText implements the encoding.TextMarshaler interface. The encoding is the same as returned by AddrPort.String, with one exception: if p.Addr() is the zero Addr, the encoding is the empty string.

        func (AddrPort) Port

        func (p AddrPort) Port() uint16

        Port returns p's port.

        func (AddrPort) String

        func (p AddrPort) String() string

        func (*AddrPort) UnmarshalBinary

        func (p *AddrPort) UnmarshalBinary(b []byte) error

        UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. It expects data in the form generated by AddrPort.MarshalBinary.

        func (*AddrPort) UnmarshalText

        func (p *AddrPort) UnmarshalText(text []byte) error

        UnmarshalText implements the encoding.TextUnmarshaler interface. The AddrPort is expected in a form generated by AddrPort.MarshalText or accepted by ParseAddrPort.

        type Prefix

        Prefix is an IP address prefix (CIDR) representing an IP network.

        The first Prefix.Bits() of Addr() are specified. The remaining bits match any address. The range of Bits() is [0,32] for IPv4 or [0,128] for IPv6.

        type Prefix struct {
            // contains filtered or unexported fields
        }
        

        func MustParsePrefix

        func MustParsePrefix(s string) Prefix

        MustParsePrefix calls ParsePrefix(s) and panics on error. It is intended for use in tests with hard-coded strings.

        func ParsePrefix

        func ParsePrefix(s string) (Prefix, error)

        ParsePrefix parses s as an IP address prefix. The string can be in the form "192.168.1.0/24" or "2001:db8::/32", the CIDR notation defined in RFC 4632 and RFC 4291. IPv6 zones are not permitted in prefixes, and an error will be returned if a zone is present.

        Note that masked address bits are not zeroed. Use Masked for that.

        func PrefixFrom

        func PrefixFrom(ip Addr, bits int) Prefix

        PrefixFrom returns a Prefix with the provided IP address and bit prefix length.

        It does not allocate. Unlike Addr.Prefix, PrefixFrom does not mask off the host bits of ip.

        If bits is less than zero or greater than ip.BitLen, Prefix.Bits will return an invalid value -1.

        func (Prefix) Addr

        func (p Prefix) Addr() Addr

        Addr returns p's IP address.

        func (Prefix) AppendTo

        func (p Prefix) AppendTo(b []byte) []byte

        AppendTo appends a text encoding of p, as generated by Prefix.MarshalText, to b and returns the extended buffer.

        func (Prefix) Bits

        func (p Prefix) Bits() int

        Bits returns p's prefix length.

        It reports -1 if invalid.

        func (Prefix) Contains

        func (p Prefix) Contains(ip Addr) bool

        Contains reports whether the network p includes ip.

        An IPv4 address will not match an IPv6 prefix. An IPv4-mapped IPv6 address will not match an IPv4 prefix. A zero-value IP will not match any prefix. If ip has an IPv6 zone, Contains returns false, because Prefixes strip zones.

        func (Prefix) IsSingleIP

        func (p Prefix) IsSingleIP() bool

        IsSingleIP reports whether p contains exactly one IP.

        func (Prefix) IsValid

        func (p Prefix) IsValid() bool

        IsValid reports whether p.Bits() has a valid range for p.Addr(). If p.Addr() is the zero Addr, IsValid returns false. Note that if p is the zero Prefix, then p.IsValid() == false.

        func (Prefix) MarshalBinary

        func (p Prefix) MarshalBinary() ([]byte, error)

        MarshalBinary implements the encoding.BinaryMarshaler interface. It returns Addr.MarshalBinary with an additional byte appended containing the prefix bits.

        func (Prefix) MarshalText

        func (p Prefix) MarshalText() ([]byte, error)

        MarshalText implements the encoding.TextMarshaler interface, The encoding is the same as returned by Prefix.String, with one exception: If p is the zero value, the encoding is the empty string.

        func (Prefix) Masked

        func (p Prefix) Masked() Prefix

        Masked returns p in its canonical form, with all but the high p.Bits() bits of p.Addr() masked off.

        If p is zero or otherwise invalid, Masked returns the zero Prefix.

        func (Prefix) Overlaps

        func (p Prefix) Overlaps(o Prefix) bool

        Overlaps reports whether p and o contain any IP addresses in common.

        If p and o are of different address families or either have a zero IP, it reports false. Like the Contains method, a prefix with an IPv4-mapped IPv6 address is still treated as an IPv6 mask.

        func (Prefix) String

        func (p Prefix) String() string

        String returns the CIDR notation of p: "<ip>/<bits>".

        func (*Prefix) UnmarshalBinary

        func (p *Prefix) UnmarshalBinary(b []byte) error

        UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. It expects data in the form generated by Prefix.MarshalBinary.

        func (*Prefix) UnmarshalText

        func (p *Prefix) UnmarshalText(text []byte) error

        UnmarshalText implements the encoding.TextUnmarshaler interface. The IP address is expected in a form accepted by ParsePrefix or generated by Prefix.MarshalText.

        rpc - Go Documentation Server
        ...

        Package rpc

        import "net/rpc"
        Overview
        Index
        Subdirectories

        Overview ▾

        Package rpc provides access to the exported methods of an object across a network or other I/O connection. A server registers an object, making it visible as a service with the name of the type of the object. After registration, exported methods of the object will be accessible remotely. A server may register multiple objects (services) of different types but it is an error to register multiple objects of the same type.

        Only methods that satisfy these criteria will be made available for remote access; other methods will be ignored:

        • the method's type is exported.
        • the method is exported.
        • the method has two arguments, both exported (or builtin) types.
        • the method's second argument is a pointer.
        • the method has return type error.

        In effect, the method must look schematically like

        func (t *T) MethodName(argType T1, replyType *T2) error
        

        where T1 and T2 can be marshaled by encoding/gob. These requirements apply even if a different codec is used. (In the future, these requirements may soften for custom codecs.)

        The method's first argument represents the arguments provided by the caller; the second argument represents the result parameters to be returned to the caller. The method's return value, if non-nil, is passed back as a string that the client sees as if created by errors.New. If an error is returned, the reply parameter will not be sent back to the client.

        The server may handle requests on a single connection by calling ServeConn. More typically it will create a network listener and call Accept or, for an HTTP listener, HandleHTTP and http.Serve.

        A client wishing to use the service establishes a connection and then invokes NewClient on the connection. The convenience function Dial (DialHTTP) performs both steps for a raw network connection (an HTTP connection). The resulting Client object has two methods, Call and Go, that specify the service and method to call, a pointer containing the arguments, and a pointer to receive the result parameters.

        The Call method waits for the remote call to complete while the Go method launches the call asynchronously and signals completion using the Call structure's Done channel.

        Unless an explicit codec is set up, package encoding/gob is used to transport the data.

        Here is a simple example. A server wishes to export an object of type Arith:

        package server
        
        import "errors"
        
        type Args struct {
        	A, B int
        }
        
        type Quotient struct {
        	Quo, Rem int
        }
        
        type Arith int
        
        func (t *Arith) Multiply(args *Args, reply *int) error {
        	*reply = args.A * args.B
        	return nil
        }
        
        func (t *Arith) Divide(args *Args, quo *Quotient) error {
        	if args.B == 0 {
        		return errors.New("divide by zero")
        	}
        	quo.Quo = args.A / args.B
        	quo.Rem = args.A % args.B
        	return nil
        }
        

        The server calls (for HTTP service):

        arith := new(Arith)
        rpc.Register(arith)
        rpc.HandleHTTP()
        l, err := net.Listen("tcp", ":1234")
        if err != nil {
        	log.Fatal("listen error:", err)
        }
        go http.Serve(l, nil)
        

        At this point, clients can see a service "Arith" with methods "Arith.Multiply" and "Arith.Divide". To invoke one, a client first dials the server:

        client, err := rpc.DialHTTP("tcp", serverAddress + ":1234")
        if err != nil {
        	log.Fatal("dialing:", err)
        }
        

        Then it can make a remote call:

        // Synchronous call
        args := &server.Args{7,8}
        var reply int
        err = client.Call("Arith.Multiply", args, &reply)
        if err != nil {
        	log.Fatal("arith error:", err)
        }
        fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply)
        

        or

        // Asynchronous call
        quotient := new(Quotient)
        divCall := client.Go("Arith.Divide", args, quotient, nil)
        replyCall := <-divCall.Done	// will be equal to divCall
        // check errors, print, etc.
        

        A server implementation will often provide a simple, type-safe wrapper for the client.

        The net/rpc package is frozen and is not accepting new features.

        Index ▾

        Package files

        client.go debug.go server.go

        Constants

        const (
            // Defaults used by HandleHTTP
            DefaultRPCPath   = "/_goRPC_"
            DefaultDebugPath = "/debug/rpc"
        )

        Variables

        DefaultServer is the default instance of *Server.

        var DefaultServer = NewServer()
        var ErrShutdown = errors.New("connection is shut down")

        func Accept

        func Accept(lis net.Listener)

        Accept accepts connections on the listener and serves requests to DefaultServer for each incoming connection. Accept blocks; the caller typically invokes it in a go statement.

        func HandleHTTP

        func HandleHTTP()

        HandleHTTP registers an HTTP handler for RPC messages to DefaultServer on DefaultRPCPath and a debugging handler on DefaultDebugPath. It is still necessary to invoke http.Serve(), typically in a go statement.

        func Register

        func Register(rcvr any) error

        Register publishes the receiver's methods in the DefaultServer.

        func RegisterName

        func RegisterName(name string, rcvr any) error

        RegisterName is like Register but uses the provided name for the type instead of the receiver's concrete type.

        func ServeCodec

        func ServeCodec(codec ServerCodec)

        ServeCodec is like ServeConn but uses the specified codec to decode requests and encode responses.

        func ServeConn

        func ServeConn(conn io.ReadWriteCloser)

        ServeConn runs the DefaultServer on a single connection. ServeConn blocks, serving the connection until the client hangs up. The caller typically invokes ServeConn in a go statement. ServeConn uses the gob wire format (see package gob) on the connection. To use an alternate codec, use ServeCodec. See NewClient's comment for information about concurrent access.

        func ServeRequest

        func ServeRequest(codec ServerCodec) error

        ServeRequest is like ServeCodec but synchronously serves a single request. It does not close the codec upon completion.

        type Call

        Call represents an active RPC.

        type Call struct {
            ServiceMethod string     // The name of the service and method to call.
            Args          any        // The argument to the function (*struct).
            Reply         any        // The reply from the function (*struct).
            Error         error      // After completion, the error status.
            Done          chan *Call // Receives *Call when Go is complete.
        }
        

        type Client

        Client represents an RPC Client. There may be multiple outstanding Calls associated with a single Client, and a Client may be used by multiple goroutines simultaneously.

        type Client struct {
            // contains filtered or unexported fields
        }
        

        func Dial

        func Dial(network, address string) (*Client, error)

        Dial connects to an RPC server at the specified network address.

        func DialHTTP

        func DialHTTP(network, address string) (*Client, error)

        DialHTTP connects to an HTTP RPC server at the specified network address listening on the default HTTP RPC path.

        func DialHTTPPath

        func DialHTTPPath(network, address, path string) (*Client, error)

        DialHTTPPath connects to an HTTP RPC server at the specified network address and path.

        func NewClient

        func NewClient(conn io.ReadWriteCloser) *Client

        NewClient returns a new Client to handle requests to the set of services at the other end of the connection. It adds a buffer to the write side of the connection so the header and payload are sent as a unit.

        The read and write halves of the connection are serialized independently, so no interlocking is required. However each half may be accessed concurrently so the implementation of conn should protect against concurrent reads or concurrent writes.

        func NewClientWithCodec

        func NewClientWithCodec(codec ClientCodec) *Client

        NewClientWithCodec is like NewClient but uses the specified codec to encode requests and decode responses.

        func (*Client) Call

        func (client *Client) Call(serviceMethod string, args any, reply any) error

        Call invokes the named function, waits for it to complete, and returns its error status.

        func (*Client) Close

        func (client *Client) Close() error

        Close calls the underlying codec's Close method. If the connection is already shutting down, ErrShutdown is returned.

        func (*Client) Go

        func (client *Client) Go(serviceMethod string, args any, reply any, done chan *Call) *Call

        Go invokes the function asynchronously. It returns the Call structure representing the invocation. The done channel will signal when the call is complete by returning the same Call object. If done is nil, Go will allocate a new channel. If non-nil, done must be buffered or Go will deliberately crash.

        type ClientCodec

        A ClientCodec implements writing of RPC requests and reading of RPC responses for the client side of an RPC session. The client calls [ClientCodec.WriteRequest] to write a request to the connection and calls [ClientCodec.ReadResponseHeader] and [ClientCodec.ReadResponseBody] in pairs to read responses. The client calls [ClientCodec.Close] when finished with the connection. ReadResponseBody may be called with a nil argument to force the body of the response to be read and then discarded. See NewClient's comment for information about concurrent access.

        type ClientCodec interface {
            WriteRequest(*Request, any) error
            ReadResponseHeader(*Response) error
            ReadResponseBody(any) error
        
            Close() error
        }

        type Request

        Request is a header written before every RPC call. It is used internally but documented here as an aid to debugging, such as when analyzing network traffic.

        type Request struct {
            ServiceMethod string // format: "Service.Method"
            Seq           uint64 // sequence number chosen by client
            // contains filtered or unexported fields
        }
        

        type Response

        Response is a header written before every RPC return. It is used internally but documented here as an aid to debugging, such as when analyzing network traffic.

        type Response struct {
            ServiceMethod string // echoes that of the Request
            Seq           uint64 // echoes that of the request
            Error         string // error, if any.
            // contains filtered or unexported fields
        }
        

        type Server

        Server represents an RPC Server.

        type Server struct {
            // contains filtered or unexported fields
        }
        

        func NewServer

        func NewServer() *Server

        NewServer returns a new Server.

        func (*Server) Accept

        func (server *Server) Accept(lis net.Listener)

        Accept accepts connections on the listener and serves requests for each incoming connection. Accept blocks until the listener returns a non-nil error. The caller typically invokes Accept in a go statement.

        func (*Server) HandleHTTP

        func (server *Server) HandleHTTP(rpcPath, debugPath string)

        HandleHTTP registers an HTTP handler for RPC messages on rpcPath, and a debugging handler on debugPath. It is still necessary to invoke http.Serve(), typically in a go statement.

        func (*Server) Register

        func (server *Server) Register(rcvr any) error

        Register publishes in the server the set of methods of the receiver value that satisfy the following conditions:

        • exported method of exported type
        • two arguments, both of exported type
        • the second argument is a pointer
        • one return value, of type error

        It returns an error if the receiver is not an exported type or has no suitable methods. It also logs the error using package log. The client accesses each method using a string of the form "Type.Method", where Type is the receiver's concrete type.

        func (*Server) RegisterName

        func (server *Server) RegisterName(name string, rcvr any) error

        RegisterName is like Register but uses the provided name for the type instead of the receiver's concrete type.

        func (*Server) ServeCodec

        func (server *Server) ServeCodec(codec ServerCodec)

        ServeCodec is like ServeConn but uses the specified codec to decode requests and encode responses.

        func (*Server) ServeConn

        func (server *Server) ServeConn(conn io.ReadWriteCloser)

        ServeConn runs the server on a single connection. ServeConn blocks, serving the connection until the client hangs up. The caller typically invokes ServeConn in a go statement. ServeConn uses the gob wire format (see package gob) on the connection. To use an alternate codec, use ServeCodec. See NewClient's comment for information about concurrent access.

        func (*Server) ServeHTTP

        func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)

        ServeHTTP implements an http.Handler that answers RPC requests.

        func (*Server) ServeRequest

        func (server *Server) ServeRequest(codec ServerCodec) error

        ServeRequest is like ServeCodec but synchronously serves a single request. It does not close the codec upon completion.

        type ServerCodec

        A ServerCodec implements reading of RPC requests and writing of RPC responses for the server side of an RPC session. The server calls [ServerCodec.ReadRequestHeader] and [ServerCodec.ReadRequestBody] in pairs to read requests from the connection, and it calls [ServerCodec.WriteResponse] to write a response back. The server calls [ServerCodec.Close] when finished with the connection. ReadRequestBody may be called with a nil argument to force the body of the request to be read and discarded. See NewClient's comment for information about concurrent access.

        type ServerCodec interface {
            ReadRequestHeader(*Request) error
            ReadRequestBody(any) error
            WriteResponse(*Response, any) error
        
            // Close can be called multiple times and must be idempotent.
            Close() error
        }

        type ServerError

        ServerError represents an error that has been returned from the remote side of the RPC connection.

        type ServerError string

        func (ServerError) Error

        func (e ServerError) Error() string

        Subdirectories

        Name Synopsis
        ..
        jsonrpc Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package.
        jsonrpc - Go Documentation Server
        ...

        Package jsonrpc

        import "net/rpc/jsonrpc"
        Overview
        Index

        Overview ▾

        Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package. For JSON-RPC 2.0 support, see https://godoc.org/?q=json-rpc+2.0

        func Dial

        func Dial(network, address string) (*rpc.Client, error)

        Dial connects to a JSON-RPC server at the specified network address.

        func NewClient

        func NewClient(conn io.ReadWriteCloser) *rpc.Client

        NewClient returns a new rpc.Client to handle requests to the set of services at the other end of the connection.

        func NewClientCodec

        func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec

        NewClientCodec returns a new rpc.ClientCodec using JSON-RPC on conn.

        func NewServerCodec

        func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec

        NewServerCodec returns a new rpc.ServerCodec using JSON-RPC on conn.

        func ServeConn

        func ServeConn(conn io.ReadWriteCloser)

        ServeConn runs the JSON-RPC server on a single connection. ServeConn blocks, serving the connection until the client hangs up. The caller typically invokes ServeConn in a go statement.

        smtp - Go Documentation Server
        ...

        Package smtp

        import "net/smtp"
        Overview
        Index
        Examples

        Overview ▾

        Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321. It also implements the following extensions:

        8BITMIME  RFC 1652
        AUTH      RFC 2554
        STARTTLS  RFC 3207
        

        Additional extensions may be handled by clients.

        The smtp package is frozen and is not accepting new features. Some external packages provide more functionality. See:

        https://godoc.org/?q=smtp
        

        Example

        Code:

        // Connect to the remote SMTP server.
        c, err := smtp.Dial("mail.example.com:25")
        if err != nil {
            log.Fatal(err)
        }
        
        // Set the sender and recipient first
        if err := c.Mail("sender@example.org"); err != nil {
            log.Fatal(err)
        }
        if err := c.Rcpt("recipient@example.net"); err != nil {
            log.Fatal(err)
        }
        
        // Send the email body.
        wc, err := c.Data()
        if err != nil {
            log.Fatal(err)
        }
        _, err = fmt.Fprintf(wc, "This is the email body")
        if err != nil {
            log.Fatal(err)
        }
        err = wc.Close()
        if err != nil {
            log.Fatal(err)
        }
        
        // Send the QUIT command and close the connection.
        err = c.Quit()
        if err != nil {
            log.Fatal(err)
        }
        

        func SendMail

        func SendMail(addr string, a Auth, from string, to []string, msg []byte) error

        SendMail connects to the server at addr, switches to TLS if possible, authenticates with the optional mechanism a if possible, and then sends an email from address from, to addresses to, with message msg. The addr must include a port, as in "mail.example.com:smtp".

        The addresses in the to parameter are the SMTP RCPT addresses.

        The msg parameter should be an RFC 822-style email with headers first, a blank line, and then the message body. The lines of msg should be CRLF terminated. The msg headers should usually include fields such as "From", "To", "Subject", and "Cc". Sending "Bcc" messages is accomplished by including an email address in the to parameter but not including it in the msg headers.

        The SendMail function and the net/smtp package are low-level mechanisms and provide no support for DKIM signing, MIME attachments (see the mime/multipart package), or other mail functionality. Higher-level packages exist outside of the standard library.

        Example

        Code:

        // Set up authentication information.
        auth := smtp.PlainAuth("", "user@example.com", "password", "mail.example.com")
        
        // Connect to the server, authenticate, set the sender and recipient,
        // and send the email all in one step.
        to := []string{"recipient@example.net"}
        msg := []byte("To: recipient@example.net\r\n" +
            "Subject: discount Gophers!\r\n" +
            "\r\n" +
            "This is the email body.\r\n")
        err := smtp.SendMail("mail.example.com:25", auth, "sender@example.org", to, msg)
        if err != nil {
            log.Fatal(err)
        }
        

        type Auth

        Auth is implemented by an SMTP authentication mechanism.

        type Auth interface {
            // Start begins an authentication with a server.
            // It returns the name of the authentication protocol
            // and optionally data to include in the initial AUTH message
            // sent to the server.
            // If it returns a non-nil error, the SMTP client aborts
            // the authentication attempt and closes the connection.
            Start(server *ServerInfo) (proto string, toServer []byte, err error)
        
            // Next continues the authentication. The server has just sent
            // the fromServer data. If more is true, the server expects a
            // response, which Next should return as toServer; otherwise
            // Next should return toServer == nil.
            // If Next returns a non-nil error, the SMTP client aborts
            // the authentication attempt and closes the connection.
            Next(fromServer []byte, more bool) (toServer []byte, err error)
        }

        func CRAMMD5Auth

        func CRAMMD5Auth(username, secret string) Auth

        CRAMMD5Auth returns an Auth that implements the CRAM-MD5 authentication mechanism as defined in RFC 2195. The returned Auth uses the given username and secret to authenticate to the server using the challenge-response mechanism.

        func PlainAuth

        func PlainAuth(identity, username, password, host string) Auth

        PlainAuth returns an Auth that implements the PLAIN authentication mechanism as defined in RFC 4616. The returned Auth uses the given username and password to authenticate to host and act as identity. Usually identity should be the empty string, to act as username.

        PlainAuth will only send the credentials if the connection is using TLS or is connected to localhost. Otherwise authentication will fail with an error, without sending the credentials.

        Example

        Code:

        // hostname is used by PlainAuth to validate the TLS certificate.
        hostname := "mail.example.com"
        auth := smtp.PlainAuth("", "user@example.com", "password", hostname)
        
        err := smtp.SendMail(hostname+":25", auth, from, recipients, msg)
        if err != nil {
            log.Fatal(err)
        }
        

        type Client

        A Client represents a client connection to an SMTP server.

        type Client struct {
            // Text is the textproto.Conn used by the Client. It is exported to allow for
            // clients to add extensions.
            Text *textproto.Conn
            // contains filtered or unexported fields
        }
        

        func Dial

        func Dial(addr string) (*Client, error)

        Dial returns a new Client connected to an SMTP server at addr. The addr must include a port, as in "mail.example.com:smtp".

        func NewClient

        func NewClient(conn net.Conn, host string) (*Client, error)

        NewClient returns a new Client using an existing connection and host as a server name to be used when authenticating.

        func (*Client) Auth

        func (c *Client) Auth(a Auth) error

        Auth authenticates a client using the provided authentication mechanism. A failed authentication closes the connection. Only servers that advertise the AUTH extension support this function.

        func (*Client) Close

        func (c *Client) Close() error

        Close closes the connection.

        func (*Client) Data

        func (c *Client) Data() (io.WriteCloser, error)

        Data issues a DATA command to the server and returns a writer that can be used to write the mail headers and body. The caller should close the writer before calling any more methods on c. A call to Data must be preceded by one or more calls to Client.Rcpt.

        func (*Client) Extension

        func (c *Client) Extension(ext string) (bool, string)

        Extension reports whether an extension is support by the server. The extension name is case-insensitive. If the extension is supported, Extension also returns a string that contains any parameters the server specifies for the extension.

        func (*Client) Hello

        func (c *Client) Hello(localName string) error

        Hello sends a HELO or EHLO to the server as the given host name. Calling this method is only necessary if the client needs control over the host name used. The client will introduce itself as "localhost" automatically otherwise. If Hello is called, it must be called before any of the other methods.

        func (*Client) Mail

        func (c *Client) Mail(from string) error

        Mail issues a MAIL command to the server using the provided email address. If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME parameter. If the server supports the SMTPUTF8 extension, Mail adds the SMTPUTF8 parameter. This initiates a mail transaction and is followed by one or more Client.Rcpt calls.

        func (*Client) Noop

        func (c *Client) Noop() error

        Noop sends the NOOP command to the server. It does nothing but check that the connection to the server is okay.

        func (*Client) Quit

        func (c *Client) Quit() error

        Quit sends the QUIT command and closes the connection to the server.

        func (*Client) Rcpt

        func (c *Client) Rcpt(to string) error

        Rcpt issues a RCPT command to the server using the provided email address. A call to Rcpt must be preceded by a call to Client.Mail and may be followed by a Client.Data call or another Rcpt call.

        func (*Client) Reset

        func (c *Client) Reset() error

        Reset sends the RSET command to the server, aborting the current mail transaction.

        func (*Client) StartTLS

        func (c *Client) StartTLS(config *tls.Config) error

        StartTLS sends the STARTTLS command and encrypts all further communication. Only servers that advertise the STARTTLS extension support this function.

        func (*Client) TLSConnectionState

        func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool)

        TLSConnectionState returns the client's TLS connection state. The return values are their zero values if Client.StartTLS did not succeed.

        func (*Client) Verify

        func (c *Client) Verify(addr string) error

        Verify checks the validity of an email address on the server. If Verify returns nil, the address is valid. A non-nil return does not necessarily indicate an invalid address. Many servers will not verify addresses for security reasons.

        type ServerInfo

        ServerInfo records information about an SMTP server.

        type ServerInfo struct {
            Name string   // SMTP server name
            TLS  bool     // using TLS, with valid certificate for Name
            Auth []string // advertised authentication mechanisms
        }
        
        textproto - Go Documentation Server
        ...

        Package textproto

        import "net/textproto"
        Overview
        Index

        Overview ▾

        Package textproto implements generic support for text-based request/response protocols in the style of HTTP, NNTP, and SMTP.

        The package provides:

        Error, which represents a numeric error response from a server.

        Pipeline, to manage pipelined requests and responses in a client.

        Reader, to read numeric response code lines, key: value headers, lines wrapped with leading spaces on continuation lines, and whole text blocks ending with a dot on a line by itself.

        Writer, to write dot-encoded text blocks.

        Conn, a convenient packaging of Reader, Writer, and Pipeline for use with a single network connection.

        Index ▾

        func CanonicalMIMEHeaderKey(s string) string
        func TrimBytes(b []byte) []byte
        func TrimString(s string) string
        type Conn
            func Dial(network, addr string) (*Conn, error)
            func NewConn(conn io.ReadWriteCloser) *Conn
            func (c *Conn) Close() error
            func (c *Conn) Cmd(format string, args ...any) (id uint, err error)
        type Error
            func (e *Error) Error() string
        type MIMEHeader
            func (h MIMEHeader) Add(key, value string)
            func (h MIMEHeader) Del(key string)
            func (h MIMEHeader) Get(key string) string
            func (h MIMEHeader) Set(key, value string)
            func (h MIMEHeader) Values(key string) []string
        type Pipeline
            func (p *Pipeline) EndRequest(id uint)
            func (p *Pipeline) EndResponse(id uint)
            func (p *Pipeline) Next() uint
            func (p *Pipeline) StartRequest(id uint)
            func (p *Pipeline) StartResponse(id uint)
        type ProtocolError
            func (p ProtocolError) Error() string
        type Reader
            func NewReader(r *bufio.Reader) *Reader
            func (r *Reader) DotReader() io.Reader
            func (r *Reader) ReadCodeLine(expectCode int) (code int, message string, err error)
            func (r *Reader) ReadContinuedLine() (string, error)
            func (r *Reader) ReadContinuedLineBytes() ([]byte, error)
            func (r *Reader) ReadDotBytes() ([]byte, error)
            func (r *Reader) ReadDotLines() ([]string, error)
            func (r *Reader) ReadLine() (string, error)
            func (r *Reader) ReadLineBytes() ([]byte, error)
            func (r *Reader) ReadMIMEHeader() (MIMEHeader, error)
            func (r *Reader) ReadResponse(expectCode int) (code int, message string, err error)
        type Writer
            func NewWriter(w *bufio.Writer) *Writer
            func (w *Writer) DotWriter() io.WriteCloser
            func (w *Writer) PrintfLine(format string, args ...any) error

        Package files

        header.go pipeline.go reader.go textproto.go writer.go

        func CanonicalMIMEHeaderKey

        func CanonicalMIMEHeaderKey(s string) string

        CanonicalMIMEHeaderKey returns the canonical format of the MIME header key s. The canonicalization converts the first letter and any letter following a hyphen to upper case; the rest are converted to lowercase. For example, the canonical key for "accept-encoding" is "Accept-Encoding". MIME header keys are assumed to be ASCII only. If s contains a space or invalid header field bytes, it is returned without modifications.

        func TrimBytes

        func TrimBytes(b []byte) []byte

        TrimBytes returns b without leading and trailing ASCII space.

        func TrimString

        func TrimString(s string) string

        TrimString returns s without leading and trailing ASCII space.

        type Conn

        A Conn represents a textual network protocol connection. It consists of a Reader and Writer to manage I/O and a Pipeline to sequence concurrent requests on the connection. These embedded types carry methods with them; see the documentation of those types for details.

        type Conn struct {
            Reader
            Writer
            Pipeline
            // contains filtered or unexported fields
        }
        

        func Dial

        func Dial(network, addr string) (*Conn, error)

        Dial connects to the given address on the given network using net.Dial and then returns a new Conn for the connection.

        func NewConn

        func NewConn(conn io.ReadWriteCloser) *Conn

        NewConn returns a new Conn using conn for I/O.

        func (*Conn) Close

        func (c *Conn) Close() error

        Close closes the connection.

        func (*Conn) Cmd

        func (c *Conn) Cmd(format string, args ...any) (id uint, err error)

        Cmd is a convenience method that sends a command after waiting its turn in the pipeline. The command text is the result of formatting format with args and appending \r\n. Cmd returns the id of the command, for use with StartResponse and EndResponse.

        For example, a client might run a HELP command that returns a dot-body by using:

        id, err := c.Cmd("HELP")
        if err != nil {
        	return nil, err
        }
        
        c.StartResponse(id)
        defer c.EndResponse(id)
        
        if _, _, err = c.ReadCodeLine(110); err != nil {
        	return nil, err
        }
        text, err := c.ReadDotBytes()
        if err != nil {
        	return nil, err
        }
        return c.ReadCodeLine(250)
        

        type Error

        An Error represents a numeric error response from a server.

        type Error struct {
            Code int
            Msg  string
        }
        

        func (*Error) Error

        func (e *Error) Error() string

        type MIMEHeader

        A MIMEHeader represents a MIME-style header mapping keys to sets of values.

        type MIMEHeader map[string][]string

        func (MIMEHeader) Add

        func (h MIMEHeader) Add(key, value string)

        Add adds the key, value pair to the header. It appends to any existing values associated with key.

        func (MIMEHeader) Del

        func (h MIMEHeader) Del(key string)

        Del deletes the values associated with key.

        func (MIMEHeader) Get

        func (h MIMEHeader) Get(key string) string

        Get gets the first value associated with the given key. It is case insensitive; CanonicalMIMEHeaderKey is used to canonicalize the provided key. If there are no values associated with the key, Get returns "". To use non-canonical keys, access the map directly.

        func (MIMEHeader) Set

        func (h MIMEHeader) Set(key, value string)

        Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key.

        func (MIMEHeader) Values

        func (h MIMEHeader) Values(key string) []string

        Values returns all values associated with the given key. It is case insensitive; CanonicalMIMEHeaderKey is used to canonicalize the provided key. To use non-canonical keys, access the map directly. The returned slice is not a copy.

        type Pipeline

        A Pipeline manages a pipelined in-order request/response sequence.

        To use a Pipeline p to manage multiple clients on a connection, each client should run:

        id := p.Next()	// take a number
        
        p.StartRequest(id)	// wait for turn to send request
        «send request»
        p.EndRequest(id)	// notify Pipeline that request is sent
        
        p.StartResponse(id)	// wait for turn to read response
        «read response»
        p.EndResponse(id)	// notify Pipeline that response is read
        

        A pipelined server can use the same calls to ensure that responses computed in parallel are written in the correct order.

        type Pipeline struct {
            // contains filtered or unexported fields
        }
        

        func (*Pipeline) EndRequest

        func (p *Pipeline) EndRequest(id uint)

        EndRequest notifies p that the request with the given id has been sent (or, if this is a server, received).

        func (*Pipeline) EndResponse

        func (p *Pipeline) EndResponse(id uint)

        EndResponse notifies p that the response with the given id has been received (or, if this is a server, sent).

        func (*Pipeline) Next

        func (p *Pipeline) Next() uint

        Next returns the next id for a request/response pair.

        func (*Pipeline) StartRequest

        func (p *Pipeline) StartRequest(id uint)

        StartRequest blocks until it is time to send (or, if this is a server, receive) the request with the given id.

        func (*Pipeline) StartResponse

        func (p *Pipeline) StartResponse(id uint)

        StartResponse blocks until it is time to receive (or, if this is a server, send) the request with the given id.

        type ProtocolError

        A ProtocolError describes a protocol violation such as an invalid response or a hung-up connection.

        type ProtocolError string

        func (ProtocolError) Error

        func (p ProtocolError) Error() string

        type Reader

        A Reader implements convenience methods for reading requests or responses from a text protocol network connection.

        type Reader struct {
            R *bufio.Reader
            // contains filtered or unexported fields
        }
        

        func NewReader

        func NewReader(r *bufio.Reader) *Reader

        NewReader returns a new Reader reading from r.

        To avoid denial of service attacks, the provided bufio.Reader should be reading from an io.LimitReader or similar Reader to bound the size of responses.

        func (*Reader) DotReader

        func (r *Reader) DotReader() io.Reader

        DotReader returns a new Reader that satisfies Reads using the decoded text of a dot-encoded block read from r. The returned Reader is only valid until the next call to a method on r.

        Dot encoding is a common framing used for data blocks in text protocols such as SMTP. The data consists of a sequence of lines, each of which ends in "\r\n". The sequence itself ends at a line containing just a dot: ".\r\n". Lines beginning with a dot are escaped with an additional dot to avoid looking like the end of the sequence.

        The decoded form returned by the Reader's Read method rewrites the "\r\n" line endings into the simpler "\n", removes leading dot escapes if present, and stops with error io.EOF after consuming (and discarding) the end-of-sequence line.

        func (*Reader) ReadCodeLine

        func (r *Reader) ReadCodeLine(expectCode int) (code int, message string, err error)

        ReadCodeLine reads a response code line of the form

        code message
        

        where code is a three-digit status code and the message extends to the rest of the line. An example of such a line is:

        220 plan9.bell-labs.com ESMTP
        

        If the prefix of the status does not match the digits in expectCode, ReadCodeLine returns with err set to &Error{code, message}. For example, if expectCode is 31, an error will be returned if the status is not in the range [310,319].

        If the response is multi-line, ReadCodeLine returns an error.

        An expectCode <= 0 disables the check of the status code.

        func (*Reader) ReadContinuedLine

        func (r *Reader) ReadContinuedLine() (string, error)

        ReadContinuedLine reads a possibly continued line from r, eliding the final trailing ASCII white space. Lines after the first are considered continuations if they begin with a space or tab character. In the returned data, continuation lines are separated from the previous line only by a single space: the newline and leading white space are removed.

        For example, consider this input:

        Line 1
          continued...
        Line 2
        

        The first call to ReadContinuedLine will return "Line 1 continued..." and the second will return "Line 2".

        Empty lines are never continued.

        func (*Reader) ReadContinuedLineBytes

        func (r *Reader) ReadContinuedLineBytes() ([]byte, error)

        ReadContinuedLineBytes is like Reader.ReadContinuedLine but returns a []byte instead of a string.

        func (*Reader) ReadDotBytes

        func (r *Reader) ReadDotBytes() ([]byte, error)

        ReadDotBytes reads a dot-encoding and returns the decoded data.

        See the documentation for the Reader.DotReader method for details about dot-encoding.

        func (*Reader) ReadDotLines

        func (r *Reader) ReadDotLines() ([]string, error)

        ReadDotLines reads a dot-encoding and returns a slice containing the decoded lines, with the final \r\n or \n elided from each.

        See the documentation for the Reader.DotReader method for details about dot-encoding.

        func (*Reader) ReadLine

        func (r *Reader) ReadLine() (string, error)

        ReadLine reads a single line from r, eliding the final \n or \r\n from the returned string.

        func (*Reader) ReadLineBytes

        func (r *Reader) ReadLineBytes() ([]byte, error)

        ReadLineBytes is like Reader.ReadLine but returns a []byte instead of a string.

        func (*Reader) ReadMIMEHeader

        func (r *Reader) ReadMIMEHeader() (MIMEHeader, error)

        ReadMIMEHeader reads a MIME-style header from r. The header is a sequence of possibly continued Key: Value lines ending in a blank line. The returned map m maps CanonicalMIMEHeaderKey(key) to a sequence of values in the same order encountered in the input.

        For example, consider this input:

        My-Key: Value 1
        Long-Key: Even
               Longer Value
        My-Key: Value 2
        

        Given that input, ReadMIMEHeader returns the map:

        map[string][]string{
        	"My-Key": {"Value 1", "Value 2"},
        	"Long-Key": {"Even Longer Value"},
        }
        

        func (*Reader) ReadResponse

        func (r *Reader) ReadResponse(expectCode int) (code int, message string, err error)

        ReadResponse reads a multi-line response of the form:

        code-message line 1
        code-message line 2
        ...
        code message line n
        

        where code is a three-digit status code. The first line starts with the code and a hyphen. The response is terminated by a line that starts with the same code followed by a space. Each line in message is separated by a newline (\n).

        See page 36 of RFC 959 (https://www.ietf.org/rfc/rfc959.txt) for details of another form of response accepted:

        code-message line 1
        message line 2
        ...
        code message line n
        

        If the prefix of the status does not match the digits in expectCode, ReadResponse returns with err set to &Error{code, message}. For example, if expectCode is 31, an error will be returned if the status is not in the range [310,319].

        An expectCode <= 0 disables the check of the status code.

        type Writer

        A Writer implements convenience methods for writing requests or responses to a text protocol network connection.

        type Writer struct {
            W *bufio.Writer
            // contains filtered or unexported fields
        }
        

        func NewWriter

        func NewWriter(w *bufio.Writer) *Writer

        NewWriter returns a new Writer writing to w.

        func (*Writer) DotWriter

        func (w *Writer) DotWriter() io.WriteCloser

        DotWriter returns a writer that can be used to write a dot-encoding to w. It takes care of inserting leading dots when necessary, translating line-ending \n into \r\n, and adding the final .\r\n line when the DotWriter is closed. The caller should close the DotWriter before the next call to a method on w.

        See the documentation for the Reader.DotReader method for details about dot-encoding.

        func (*Writer) PrintfLine

        func (w *Writer) PrintfLine(format string, args ...any) error

        PrintfLine writes the formatted output followed by \r\n.

        url - Go Documentation Server
        ...

        Package url

        import "net/url"
        Overview
        Index
        Examples

        Overview ▾

        Package url parses URLs and implements query escaping.

        Index ▾

        func JoinPath(base string, elem ...string) (result string, err error)
        func PathEscape(s string) string
        func PathUnescape(s string) (string, error)
        func QueryEscape(s string) string
        func QueryUnescape(s string) (string, error)
        type Error
            func (e *Error) Error() string
            func (e *Error) Temporary() bool
            func (e *Error) Timeout() bool
            func (e *Error) Unwrap() error
        type EscapeError
            func (e EscapeError) Error() string
        type InvalidHostError
            func (e InvalidHostError) Error() string
        type URL
            func Parse(rawURL string) (*URL, error)
            func ParseRequestURI(rawURL string) (*URL, error)
            func (u *URL) EscapedFragment() string
            func (u *URL) EscapedPath() string
            func (u *URL) Hostname() string
            func (u *URL) IsAbs() bool
            func (u *URL) JoinPath(elem ...string) *URL
            func (u *URL) MarshalBinary() (text []byte, err error)
            func (u *URL) Parse(ref string) (*URL, error)
            func (u *URL) Port() string
            func (u *URL) Query() Values
            func (u *URL) Redacted() string
            func (u *URL) RequestURI() string
            func (u *URL) ResolveReference(ref *URL) *URL
            func (u *URL) String() string
            func (u *URL) UnmarshalBinary(text []byte) error
        type Userinfo
            func User(username string) *Userinfo
            func UserPassword(username, password string) *Userinfo
            func (u *Userinfo) Password() (string, bool)
            func (u *Userinfo) String() string
            func (u *Userinfo) Username() string
        type Values
            func ParseQuery(query string) (Values, error)
            func (v Values) Add(key, value string)
            func (v Values) Del(key string)
            func (v Values) Encode() string
            func (v Values) Get(key string) string
            func (v Values) Has(key string) bool
            func (v Values) Set(key, value string)

        Package files

        url.go

        func JoinPath

        func JoinPath(base string, elem ...string) (result string, err error)

        JoinPath returns a URL string with the provided path elements joined to the existing path of base and the resulting path cleaned of any ./ or ../ elements.

        func PathEscape

        func PathEscape(s string) string

        PathEscape escapes the string so it can be safely placed inside a URL path segment, replacing special characters (including /) with %XX sequences as needed.

        Example

        Code:

        path := url.PathEscape("my/cool+blog&about,stuff")
        fmt.Println(path)
        
        

        Output:

        my%2Fcool+blog&about%2Cstuff
        

        func PathUnescape

        func PathUnescape(s string) (string, error)

        PathUnescape does the inverse transformation of PathEscape, converting each 3-byte encoded substring of the form "%AB" into the hex-decoded byte 0xAB. It returns an error if any % is not followed by two hexadecimal digits.

        PathUnescape is identical to QueryUnescape except that it does not unescape '+' to ' ' (space).

        Example

        Code:

        escapedPath := "my%2Fcool+blog&about%2Cstuff"
        path, err := url.PathUnescape(escapedPath)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(path)
        
        

        Output:

        my/cool+blog&about,stuff
        

        func QueryEscape

        func QueryEscape(s string) string

        QueryEscape escapes the string so it can be safely placed inside a URL query.

        Example

        Code:

        query := url.QueryEscape("my/cool+blog&about,stuff")
        fmt.Println(query)
        
        

        Output:

        my%2Fcool%2Bblog%26about%2Cstuff
        

        func QueryUnescape

        func QueryUnescape(s string) (string, error)

        QueryUnescape does the inverse transformation of QueryEscape, converting each 3-byte encoded substring of the form "%AB" into the hex-decoded byte 0xAB. It returns an error if any % is not followed by two hexadecimal digits.

        Example

        Code:

        escapedQuery := "my%2Fcool%2Bblog%26about%2Cstuff"
        query, err := url.QueryUnescape(escapedQuery)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(query)
        
        

        Output:

        my/cool+blog&about,stuff
        

        type Error

        Error reports an error and the operation and URL that caused it.

        type Error struct {
            Op  string
            URL string
            Err error
        }
        

        func (*Error) Error

        func (e *Error) Error() string

        func (*Error) Temporary

        func (e *Error) Temporary() bool

        func (*Error) Timeout

        func (e *Error) Timeout() bool

        func (*Error) Unwrap

        func (e *Error) Unwrap() error

        type EscapeError

        type EscapeError string

        func (EscapeError) Error

        func (e EscapeError) Error() string

        type InvalidHostError

        type InvalidHostError string

        func (InvalidHostError) Error

        func (e InvalidHostError) Error() string

        type URL

        A URL represents a parsed URL (technically, a URI reference).

        The general form represented is:

        [scheme:][//[userinfo@]host][/]path[?query][#fragment]
        

        URLs that do not start with a slash after the scheme are interpreted as:

        scheme:opaque[?query][#fragment]
        

        The Host field contains the host and port subcomponents of the URL. When the port is present, it is separated from the host with a colon. When the host is an IPv6 address, it must be enclosed in square brackets: "[fe80::1]:80". The net.JoinHostPort function combines a host and port into a string suitable for the Host field, adding square brackets to the host when necessary.

        Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. A consequence is that it is impossible to tell which slashes in the Path were slashes in the raw URL and which were %2f. This distinction is rarely important, but when it is, the code should use the URL.EscapedPath method, which preserves the original encoding of Path.

        The RawPath field is an optional field which is only set when the default encoding of Path is different from the escaped path. See the EscapedPath method for more details.

        URL's String method uses the EscapedPath method to obtain the path.

        type URL struct {
            Scheme      string
            Opaque      string    // encoded opaque data
            User        *Userinfo // username and password information
            Host        string    // host or host:port (see Hostname and Port methods)
            Path        string    // path (relative paths may omit leading slash)
            RawPath     string    // encoded path hint (see EscapedPath method)
            OmitHost    bool      // do not emit empty host (authority)
            ForceQuery  bool      // append a query ('?') even if RawQuery is empty
            RawQuery    string    // encoded query values, without '?'
            Fragment    string    // fragment for references, without '#'
            RawFragment string    // encoded fragment hint (see EscapedFragment method)
        }
        

        Example

        Code:

        u, err := url.Parse("http://bing.com/search?q=dotnet")
        if err != nil {
            log.Fatal(err)
        }
        u.Scheme = "https"
        u.Host = "google.com"
        q := u.Query()
        q.Set("q", "golang")
        u.RawQuery = q.Encode()
        fmt.Println(u)
        

        Output:

        https://google.com/search?q=golang
        

        Example (Roundtrip)

        Code:

        // Parse + String preserve the original encoding.
        u, err := url.Parse("https://example.com/foo%2fbar")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(u.Path)
        fmt.Println(u.RawPath)
        fmt.Println(u.String())
        

        Output:

        /foo/bar
        /foo%2fbar
        https://example.com/foo%2fbar
        

        func Parse

        func Parse(rawURL string) (*URL, error)

        Parse parses a raw url into a URL structure.

        The url may be relative (a path, without a host) or absolute (starting with a scheme). Trying to parse a hostname and path without a scheme is invalid but may not necessarily return an error, due to parsing ambiguities.

        func ParseRequestURI

        func ParseRequestURI(rawURL string) (*URL, error)

        ParseRequestURI parses a raw url into a URL structure. It assumes that url was received in an HTTP request, so the url is interpreted only as an absolute URI or an absolute path. The string url is assumed not to have a #fragment suffix. (Web browsers strip #fragment before sending the URL to a web server.)

        func (*URL) EscapedFragment

        func (u *URL) EscapedFragment() string

        EscapedFragment returns the escaped form of u.Fragment. In general there are multiple possible escaped forms of any fragment. EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. Otherwise EscapedFragment ignores u.RawFragment and computes an escaped form on its own. The URL.String method uses EscapedFragment to construct its result. In general, code should call EscapedFragment instead of reading u.RawFragment directly.

        Example

        Code:

        u, err := url.Parse("http://example.com/#x/y%2Fz")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("Fragment:", u.Fragment)
        fmt.Println("RawFragment:", u.RawFragment)
        fmt.Println("EscapedFragment:", u.EscapedFragment())
        

        Output:

        Fragment: x/y/z
        RawFragment: x/y%2Fz
        EscapedFragment: x/y%2Fz
        

        func (*URL) EscapedPath

        func (u *URL) EscapedPath() string

        EscapedPath returns the escaped form of u.Path. In general there are multiple possible escaped forms of any path. EscapedPath returns u.RawPath when it is a valid escaping of u.Path. Otherwise EscapedPath ignores u.RawPath and computes an escaped form on its own. The URL.String and URL.RequestURI methods use EscapedPath to construct their results. In general, code should call EscapedPath instead of reading u.RawPath directly.

        Example

        Code:

        u, err := url.Parse("http://example.com/x/y%2Fz")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("Path:", u.Path)
        fmt.Println("RawPath:", u.RawPath)
        fmt.Println("EscapedPath:", u.EscapedPath())
        

        Output:

        Path: /x/y/z
        RawPath: /x/y%2Fz
        EscapedPath: /x/y%2Fz
        

        func (*URL) Hostname

        func (u *URL) Hostname() string

        Hostname returns u.Host, stripping any valid port number if present.

        If the result is enclosed in square brackets, as literal IPv6 addresses are, the square brackets are removed from the result.

        Example

        Code:

        u, err := url.Parse("https://example.org:8000/path")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(u.Hostname())
        u, err = url.Parse("https://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:17000")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(u.Hostname())
        

        Output:

        example.org
        2001:0db8:85a3:0000:0000:8a2e:0370:7334
        

        func (*URL) IsAbs

        func (u *URL) IsAbs() bool

        IsAbs reports whether the URL is absolute. Absolute means that it has a non-empty scheme.

        Example

        Code:

        u := url.URL{Host: "example.com", Path: "foo"}
        fmt.Println(u.IsAbs())
        u.Scheme = "http"
        fmt.Println(u.IsAbs())
        

        Output:

        false
        true
        

        func (*URL) JoinPath

        func (u *URL) JoinPath(elem ...string) *URL

        JoinPath returns a new URL with the provided path elements joined to any existing path and the resulting path cleaned of any ./ or ../ elements. Any sequences of multiple / characters will be reduced to a single /.

        func (*URL) MarshalBinary

        func (u *URL) MarshalBinary() (text []byte, err error)

        Example

        Code:

        u, _ := url.Parse("https://example.org")
        b, err := u.MarshalBinary()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s\n", b)
        

        Output:

        https://example.org
        

        func (*URL) Parse

        func (u *URL) Parse(ref string) (*URL, error)

        Parse parses a URL in the context of the receiver. The provided URL may be relative or absolute. Parse returns nil, err on parse failure, otherwise its return value is the same as URL.ResolveReference.

        Example

        Code:

        u, err := url.Parse("https://example.org")
        if err != nil {
            log.Fatal(err)
        }
        rel, err := u.Parse("/foo")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(rel)
        _, err = u.Parse(":foo")
        if _, ok := err.(*url.Error); !ok {
            log.Fatal(err)
        }
        

        Output:

        https://example.org/foo
        

        func (*URL) Port

        func (u *URL) Port() string

        Port returns the port part of u.Host, without the leading colon.

        If u.Host doesn't contain a valid numeric port, Port returns an empty string.

        Example

        Code:

        u, err := url.Parse("https://example.org")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(u.Port())
        u, err = url.Parse("https://example.org:8080")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(u.Port())
        

        Output:

        8080
        

        func (*URL) Query

        func (u *URL) Query() Values

        Query parses RawQuery and returns the corresponding values. It silently discards malformed value pairs. To check errors use ParseQuery.

        Example

        Code:

        u, err := url.Parse("https://example.org/?a=1&a=2&b=&=3&&&&")
        if err != nil {
            log.Fatal(err)
        }
        q := u.Query()
        fmt.Println(q["a"])
        fmt.Println(q.Get("b"))
        fmt.Println(q.Get(""))
        

        Output:

        [1 2]
        
        3
        

        func (*URL) Redacted

        func (u *URL) Redacted() string

        Redacted is like URL.String but replaces any password with "xxxxx". Only the password in u.User is redacted.

        Example

        Code:

        u := &url.URL{
            Scheme: "https",
            User:   url.UserPassword("user", "password"),
            Host:   "example.com",
            Path:   "foo/bar",
        }
        fmt.Println(u.Redacted())
        u.User = url.UserPassword("me", "newerPassword")
        fmt.Println(u.Redacted())
        

        Output:

        https://user:xxxxx@example.com/foo/bar
        https://me:xxxxx@example.com/foo/bar
        

        func (*URL) RequestURI

        func (u *URL) RequestURI() string

        RequestURI returns the encoded path?query or opaque?query string that would be used in an HTTP request for u.

        Example

        Code:

        u, err := url.Parse("https://example.org/path?foo=bar")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(u.RequestURI())
        

        Output:

        /path?foo=bar
        

        func (*URL) ResolveReference

        func (u *URL) ResolveReference(ref *URL) *URL

        ResolveReference resolves a URI reference to an absolute URI from an absolute base URI u, per RFC 3986 Section 5.2. The URI reference may be relative or absolute. ResolveReference always returns a new URL instance, even if the returned URL is identical to either the base or reference. If ref is an absolute URL, then ResolveReference ignores base and returns a copy of ref.

        Example

        Code:

        u, err := url.Parse("../../..//search?q=dotnet")
        if err != nil {
            log.Fatal(err)
        }
        base, err := url.Parse("http://example.com/directory/")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(base.ResolveReference(u))
        

        Output:

        http://example.com/search?q=dotnet
        

        func (*URL) String

        func (u *URL) String() string

        String reassembles the URL into a valid URL string. The general form of the result is one of:

        scheme:opaque?query#fragment
        scheme://userinfo@host/path?query#fragment
        

        If u.Opaque is non-empty, String uses the first form; otherwise it uses the second form. Any non-ASCII characters in host are escaped. To obtain the path, String uses u.EscapedPath().

        In the second form, the following rules apply:

        • if u.Scheme is empty, scheme: is omitted.
        • if u.User is nil, userinfo@ is omitted.
        • if u.Host is empty, host/ is omitted.
        • if u.Scheme and u.Host are empty and u.User is nil, the entire scheme://userinfo@host/ is omitted.
        • if u.Host is non-empty and u.Path begins with a /, the form host/path does not add its own /.
        • if u.RawQuery is empty, ?query is omitted.
        • if u.Fragment is empty, #fragment is omitted.

        Example

        Code:

        u := &url.URL{
            Scheme:   "https",
            User:     url.UserPassword("me", "pass"),
            Host:     "example.com",
            Path:     "foo/bar",
            RawQuery: "x=1&y=2",
            Fragment: "anchor",
        }
        fmt.Println(u.String())
        u.Opaque = "opaque"
        fmt.Println(u.String())
        

        Output:

        https://me:pass@example.com/foo/bar?x=1&y=2#anchor
        https:opaque?x=1&y=2#anchor
        

        func (*URL) UnmarshalBinary

        func (u *URL) UnmarshalBinary(text []byte) error

        Example

        Code:

        u := &url.URL{}
        err := u.UnmarshalBinary([]byte("https://example.org/foo"))
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s\n", u)
        

        Output:

        https://example.org/foo
        

        type Userinfo

        The Userinfo type is an immutable encapsulation of username and password details for a URL. An existing Userinfo value is guaranteed to have a username set (potentially empty, as allowed by RFC 2396), and optionally a password.

        type Userinfo struct {
            // contains filtered or unexported fields
        }
        

        func User

        func User(username string) *Userinfo

        User returns a Userinfo containing the provided username and no password set.

        func UserPassword

        func UserPassword(username, password string) *Userinfo

        UserPassword returns a Userinfo containing the provided username and password.

        This functionality should only be used with legacy web sites. RFC 2396 warns that interpreting Userinfo this way “is NOT RECOMMENDED, because the passing of authentication information in clear text (such as URI) has proven to be a security risk in almost every case where it has been used.”

        func (*Userinfo) Password

        func (u *Userinfo) Password() (string, bool)

        Password returns the password in case it is set, and whether it is set.

        func (*Userinfo) String

        func (u *Userinfo) String() string

        String returns the encoded userinfo information in the standard form of "username[:password]".

        func (*Userinfo) Username

        func (u *Userinfo) Username() string

        Username returns the username.

        type Values

        Values maps a string key to a list of values. It is typically used for query parameters and form values. Unlike in the http.Header map, the keys in a Values map are case-sensitive.

        type Values map[string][]string

        Example

        Code:

        v := url.Values{}
        v.Set("name", "Ava")
        v.Add("friend", "Jess")
        v.Add("friend", "Sarah")
        v.Add("friend", "Zoe")
        // v.Encode() == "name=Ava&friend=Jess&friend=Sarah&friend=Zoe"
        fmt.Println(v.Get("name"))
        fmt.Println(v.Get("friend"))
        fmt.Println(v["friend"])
        

        Output:

        Ava
        Jess
        [Jess Sarah Zoe]
        

        func ParseQuery

        func ParseQuery(query string) (Values, error)

        ParseQuery parses the URL-encoded query string and returns a map listing the values specified for each key. ParseQuery always returns a non-nil map containing all the valid query parameters found; err describes the first decoding error encountered, if any.

        Query is expected to be a list of key=value settings separated by ampersands. A setting without an equals sign is interpreted as a key set to an empty value. Settings containing a non-URL-encoded semicolon are considered invalid.

        Example

        Code:

        m, err := url.ParseQuery(`x=1&y=2&y=3`)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(toJSON(m))
        

        Output:

        {"x":["1"], "y":["2", "3"]}
        

        func (Values) Add

        func (v Values) Add(key, value string)

        Add adds the value to key. It appends to any existing values associated with key.

        Example

        Code:

        v := url.Values{}
        v.Add("cat sounds", "meow")
        v.Add("cat sounds", "mew")
        v.Add("cat sounds", "mau")
        fmt.Println(v["cat sounds"])
        
        

        Output:

        [meow mew mau]
        

        func (Values) Del

        func (v Values) Del(key string)

        Del deletes the values associated with key.

        Example

        Code:

        v := url.Values{}
        v.Add("cat sounds", "meow")
        v.Add("cat sounds", "mew")
        v.Add("cat sounds", "mau")
        fmt.Println(v["cat sounds"])
        
        v.Del("cat sounds")
        fmt.Println(v["cat sounds"])
        
        

        Output:

        [meow mew mau]
        []
        

        func (Values) Encode

        func (v Values) Encode() string

        Encode encodes the values into “URL encoded” form ("bar=baz&foo=quux") sorted by key.

        Example

        Code:

        v := url.Values{}
        v.Add("cat sounds", "meow")
        v.Add("cat sounds", "mew/")
        v.Add("cat sounds", "mau$")
        fmt.Println(v.Encode())
        
        

        Output:

        cat+sounds=meow&cat+sounds=mew%2F&cat+sounds=mau%24
        

        func (Values) Get

        func (v Values) Get(key string) string

        Get gets the first value associated with the given key. If there are no values associated with the key, Get returns the empty string. To access multiple values, use the map directly.

        Example

        Code:

        v := url.Values{}
        v.Add("cat sounds", "meow")
        v.Add("cat sounds", "mew")
        v.Add("cat sounds", "mau")
        fmt.Printf("%q\n", v.Get("cat sounds"))
        fmt.Printf("%q\n", v.Get("dog sounds"))
        
        

        Output:

        "meow"
        ""
        

        func (Values) Has

        func (v Values) Has(key string) bool

        Has checks whether a given key is set.

        Example

        Code:

        v := url.Values{}
        v.Add("cat sounds", "meow")
        v.Add("cat sounds", "mew")
        v.Add("cat sounds", "mau")
        fmt.Println(v.Has("cat sounds"))
        fmt.Println(v.Has("dog sounds"))
        
        

        Output:

        true
        false
        

        func (Values) Set

        func (v Values) Set(key, value string)

        Set sets the key to value. It replaces any existing values.

        Example

        Code:

        v := url.Values{}
        v.Add("cat sounds", "meow")
        v.Add("cat sounds", "mew")
        v.Add("cat sounds", "mau")
        fmt.Println(v["cat sounds"])
        
        v.Set("cat sounds", "meow")
        fmt.Println(v["cat sounds"])
        
        

        Output:

        [meow mew mau]
        [meow]
        
        os - Go Documentation Server
        ...

        Package os

        Overview ▾

        Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is available within the error. For example, if a call that takes a file name fails, such as Open or Stat, the error will include the failing file name when printed and will be of type *PathError, which may be unpacked for more information.

        The os interface is intended to be uniform across all operating systems. Features not generally available appear in the system-specific package syscall.

        Here is a simple example, opening a file and reading some of it.

        file, err := os.Open("file.go") // For read access.
        if err != nil {
        	log.Fatal(err)
        }
        

        If the open fails, the error string will be self-explanatory, like

        open file.go: no such file or directory
        

        The file's data can then be read into a slice of bytes. Read and Write take their byte counts from the length of the argument slice.

        data := make([]byte, 100)
        count, err := file.Read(data)
        if err != nil {
        	log.Fatal(err)
        }
        fmt.Printf("read %d bytes: %q\n", count, data[:count])
        

        Note: The maximum number of concurrent operations on a File may be limited by the OS or the system. The number should be high, but exceeding it may degrade performance or cause other issues.

        Index ▾

        Constants
        Variables
        func Chdir(dir string) error
        func Chmod(name string, mode FileMode) error
        func Chown(name string, uid, gid int) error
        func Chtimes(name string, atime time.Time, mtime time.Time) error
        func Clearenv()
        func DirFS(dir string) fs.FS
        func Environ() []string
        func Executable() (string, error)
        func Exit(code int)
        func Expand(s string, mapping func(string) string) string
        func ExpandEnv(s string) string
        func Getegid() int
        func Getenv(key string) string
        func Geteuid() int
        func Getgid() int
        func Getgroups() ([]int, error)
        func Getpagesize() int
        func Getpid() int
        func Getppid() int
        func Getuid() int
        func Getwd() (dir string, err error)
        func Hostname() (name string, err error)
        func IsExist(err error) bool
        func IsNotExist(err error) bool
        func IsPathSeparator(c uint8) bool
        func IsPermission(err error) bool
        func IsTimeout(err error) bool
        func Lchown(name string, uid, gid int) error
        func Link(oldname, newname string) error
        func LookupEnv(key string) (string, bool)
        func Mkdir(name string, perm FileMode) error
        func MkdirAll(path string, perm FileMode) error
        func MkdirTemp(dir, pattern string) (string, error)
        func NewSyscallError(syscall string, err error) error
        func Pipe() (r *File, w *File, err error)
        func ReadFile(name string) ([]byte, error)
        func Readlink(name string) (string, error)
        func Remove(name string) error
        func RemoveAll(path string) error
        func Rename(oldpath, newpath string) error
        func SameFile(fi1, fi2 FileInfo) bool
        func Setenv(key, value string) error
        func Symlink(oldname, newname string) error
        func TempDir() string
        func Truncate(name string, size int64) error
        func Unsetenv(key string) error
        func UserCacheDir() (string, error)
        func UserConfigDir() (string, error)
        func UserHomeDir() (string, error)
        func WriteFile(name string, data []byte, perm FileMode) error
        type DirEntry
            func ReadDir(name string) ([]DirEntry, error)
        type File
            func Create(name string) (*File, error)
            func CreateTemp(dir, pattern string) (*File, error)
            func NewFile(fd uintptr, name string) *File
            func Open(name string) (*File, error)
            func OpenFile(name string, flag int, perm FileMode) (*File, error)
            func (f *File) Chdir() error
            func (f *File) Chmod(mode FileMode) error
            func (f *File) Chown(uid, gid int) error
            func (f *File) Close() error
            func (f *File) Fd() uintptr
            func (f *File) Name() string
            func (f *File) Read(b []byte) (n int, err error)
            func (f *File) ReadAt(b []byte, off int64) (n int, err error)
            func (f *File) ReadDir(n int) ([]DirEntry, error)
            func (f *File) ReadFrom(r io.Reader) (n int64, err error)
            func (f *File) Readdir(n int) ([]FileInfo, error)
            func (f *File) Readdirnames(n int) (names []string, err error)
            func (f *File) Seek(offset int64, whence int) (ret int64, err error)
            func (f *File) SetDeadline(t time.Time) error
            func (f *File) SetReadDeadline(t time.Time) error
            func (f *File) SetWriteDeadline(t time.Time) error
            func (f *File) Stat() (FileInfo, error)
            func (f *File) Sync() error
            func (f *File) SyscallConn() (syscall.RawConn, error)
            func (f *File) Truncate(size int64) error
            func (f *File) Write(b []byte) (n int, err error)
            func (f *File) WriteAt(b []byte, off int64) (n int, err error)
            func (f *File) WriteString(s string) (n int, err error)
            func (f *File) WriteTo(w io.Writer) (n int64, err error)
        type FileInfo
            func Lstat(name string) (FileInfo, error)
            func Stat(name string) (FileInfo, error)
        type FileMode
        type LinkError
            func (e *LinkError) Error() string
            func (e *LinkError) Unwrap() error
        type PathError
        type ProcAttr
        type Process
            func FindProcess(pid int) (*Process, error)
            func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)
            func (p *Process) Kill() error
            func (p *Process) Release() error
            func (p *Process) Signal(sig Signal) error
            func (p *Process) Wait() (*ProcessState, error)
        type ProcessState
            func (p *ProcessState) ExitCode() int
            func (p *ProcessState) Exited() bool
            func (p *ProcessState) Pid() int
            func (p *ProcessState) String() string
            func (p *ProcessState) Success() bool
            func (p *ProcessState) Sys() any
            func (p *ProcessState) SysUsage() any
            func (p *ProcessState) SystemTime() time.Duration
            func (p *ProcessState) UserTime() time.Duration
        type Signal
        type SyscallError
            func (e *SyscallError) Error() string
            func (e *SyscallError) Timeout() bool
            func (e *SyscallError) Unwrap() error

        Package files

        dir.go dir_unix.go dirent_linux.go endian_little.go env.go error.go error_errno.go error_posix.go exec.go exec_posix.go exec_unix.go executable.go executable_procfs.go file.go file_open_unix.go file_posix.go file_unix.go getwd.go path.go path_unix.go pipe2_unix.go proc.go rawconn.go removeall_at.go stat.go stat_linux.go stat_unix.go sticky_notbsd.go sys.go sys_linux.go sys_unix.go tempfile.go types.go types_unix.go wait_waitid.go zero_copy_linux.go

        Constants

        Flags to OpenFile wrapping those of the underlying system. Not all flags may be implemented on a given system.

        const (
            // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
            O_RDONLY int = syscall.O_RDONLY // open the file read-only.
            O_WRONLY int = syscall.O_WRONLY // open the file write-only.
            O_RDWR   int = syscall.O_RDWR   // open the file read-write.
            // The remaining values may be or'ed in to control behavior.
            O_APPEND int = syscall.O_APPEND // append data to the file when writing.
            O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
            O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist.
            O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
            O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.
        )

        Seek whence values.

        Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.

        const (
            SEEK_SET int = 0 // seek relative to the origin of the file
            SEEK_CUR int = 1 // seek relative to the current offset
            SEEK_END int = 2 // seek relative to the end
        )
        const (
            PathSeparator     = '/' // OS-specific path separator
            PathListSeparator = ':' // OS-specific path list separator
        )

        The defined file mode bits are the most significant bits of the FileMode. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

        const (
            // The single letters are the abbreviations
            // used by the String method's formatting.
            ModeDir        = fs.ModeDir        // d: is a directory
            ModeAppend     = fs.ModeAppend     // a: append-only
            ModeExclusive  = fs.ModeExclusive  // l: exclusive use
            ModeTemporary  = fs.ModeTemporary  // T: temporary file; Plan 9 only
            ModeSymlink    = fs.ModeSymlink    // L: symbolic link
            ModeDevice     = fs.ModeDevice     // D: device file
            ModeNamedPipe  = fs.ModeNamedPipe  // p: named pipe (FIFO)
            ModeSocket     = fs.ModeSocket     // S: Unix domain socket
            ModeSetuid     = fs.ModeSetuid     // u: setuid
            ModeSetgid     = fs.ModeSetgid     // g: setgid
            ModeCharDevice = fs.ModeCharDevice // c: Unix character device, when ModeDevice is set
            ModeSticky     = fs.ModeSticky     // t: sticky
            ModeIrregular  = fs.ModeIrregular  // ?: non-regular file; nothing else is known about this file
        
            // Mask for the type bits. For regular files, none will be set.
            ModeType = fs.ModeType
        
            ModePerm = fs.ModePerm // Unix permission bits, 0o777
        )

        DevNull is the name of the operating system's “null device.” On Unix-like systems, it is "/dev/null"; on Windows, "NUL".

        const DevNull = "/dev/null"

        Variables

        Portable analogs of some common system call errors.

        Errors returned from this package may be tested against these errors with errors.Is.

        var (
            // ErrInvalid indicates an invalid argument.
            // Methods on File will return this error when the receiver is nil.
            ErrInvalid = fs.ErrInvalid // "invalid argument"
        
            ErrPermission = fs.ErrPermission // "permission denied"
            ErrExist      = fs.ErrExist      // "file already exists"
            ErrNotExist   = fs.ErrNotExist   // "file does not exist"
            ErrClosed     = fs.ErrClosed     // "file already closed"
        
            ErrNoDeadline       = errNoDeadline()       // "file type does not support deadline"
            ErrDeadlineExceeded = errDeadlineExceeded() // "i/o timeout"
        )

        Stdin, Stdout, and Stderr are open Files pointing to the standard input, standard output, and standard error file descriptors.

        Note that the Go runtime writes to standard error for panics and crashes; closing Stderr may cause those messages to go elsewhere, perhaps to a file opened later.

        var (
            Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
            Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
            Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
        )

        Args hold the command-line arguments, starting with the program name.

        var Args []string

        ErrProcessDone indicates a Process has finished.

        var ErrProcessDone = errors.New("os: process already finished")

        func Chdir

        func Chdir(dir string) error

        Chdir changes the current working directory to the named directory. If there is an error, it will be of type *PathError.

        func Chmod

        func Chmod(name string, mode FileMode) error

        Chmod changes the mode of the named file to mode. If the file is a symbolic link, it changes the mode of the link's target. If there is an error, it will be of type *PathError.

        A different subset of the mode bits are used, depending on the operating system.

        On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and ModeSticky are used.

        On Windows, only the 0200 bit (owner writable) of mode is used; it controls whether the file's read-only attribute is set or cleared. The other bits are currently unused. For compatibility with Go 1.12 and earlier, use a non-zero mode. Use mode 0400 for a read-only file and 0600 for a readable+writable file.

        On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive, and ModeTemporary are used.

        Example

        Code:

        if err := os.Chmod("some-filename", 0644); err != nil {
            log.Fatal(err)
        }
        

        func Chown

        func Chown(name string, uid, gid int) error

        Chown changes the numeric uid and gid of the named file. If the file is a symbolic link, it changes the uid and gid of the link's target. A uid or gid of -1 means to not change that value. If there is an error, it will be of type *PathError.

        On Windows or Plan 9, Chown always returns the syscall.EWINDOWS or EPLAN9 error, wrapped in *PathError.

        func Chtimes

        func Chtimes(name string, atime time.Time, mtime time.Time) error

        Chtimes changes the access and modification times of the named file, similar to the Unix utime() or utimes() functions. A zero time.Time value will leave the corresponding file time unchanged.

        The underlying filesystem may truncate or round the values to a less precise time unit. If there is an error, it will be of type *PathError.

        Example

        Code:

        mtime := time.Date(2006, time.February, 1, 3, 4, 5, 0, time.UTC)
        atime := time.Date(2007, time.March, 2, 4, 5, 6, 0, time.UTC)
        if err := os.Chtimes("some-filename", atime, mtime); err != nil {
            log.Fatal(err)
        }
        

        func Clearenv

        func Clearenv()

        Clearenv deletes all environment variables.

        func DirFS

        func DirFS(dir string) fs.FS

        DirFS returns a file system (an fs.FS) for the tree of files rooted at the directory dir.

        Note that DirFS("/prefix") only guarantees that the Open calls it makes to the operating system will begin with "/prefix": DirFS("/prefix").Open("file") is the same as os.Open("/prefix/file"). So if /prefix/file is a symbolic link pointing outside the /prefix tree, then using DirFS does not stop the access any more than using os.Open does. Additionally, the root of the fs.FS returned for a relative path, DirFS("prefix"), will be affected by later calls to Chdir. DirFS is therefore not a general substitute for a chroot-style security mechanism when the directory tree contains arbitrary content.

        The directory dir must not be "".

        The result implements io/fs.StatFS, io/fs.ReadFileFS and io/fs.ReadDirFS.

        func Environ

        func Environ() []string

        Environ returns a copy of strings representing the environment, in the form "key=value".

        func Executable

        func Executable() (string, error)

        Executable returns the path name for the executable that started the current process. There is no guarantee that the path is still pointing to the correct executable. If a symlink was used to start the process, depending on the operating system, the result might be the symlink or the path it pointed to. If a stable result is needed, path/filepath.EvalSymlinks might help.

        Executable returns an absolute path unless an error occurred.

        The main use case is finding resources located relative to an executable.

        func Exit

        func Exit(code int)

        Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run.

        For portability, the status code should be in the range [0, 125].

        func Expand

        func Expand(s string, mapping func(string) string) string

        Expand replaces ${var} or $var in the string based on the mapping function. For example, os.ExpandEnv(s) is equivalent to os.Expand(s, os.Getenv).

        Example

        Code:

        mapper := func(placeholderName string) string {
            switch placeholderName {
            case "DAY_PART":
                return "morning"
            case "NAME":
                return "Gopher"
            }
        
            return ""
        }
        
        fmt.Println(os.Expand("Good ${DAY_PART}, $NAME!", mapper))
        
        

        Output:

        Good morning, Gopher!
        

        func ExpandEnv

        func ExpandEnv(s string) string

        ExpandEnv replaces ${var} or $var in the string according to the values of the current environment variables. References to undefined variables are replaced by the empty string.

        Example

        Code:

        os.Setenv("NAME", "gopher")
        os.Setenv("BURROW", "/usr/gopher")
        
        fmt.Println(os.ExpandEnv("$NAME lives in ${BURROW}."))
        
        

        Output:

        gopher lives in /usr/gopher.
        

        func Getegid

        func Getegid() int

        Getegid returns the numeric effective group id of the caller.

        On Windows, it returns -1.

        func Getenv

        func Getenv(key string) string

        Getenv retrieves the value of the environment variable named by the key. It returns the value, which will be empty if the variable is not present. To distinguish between an empty value and an unset value, use LookupEnv.

        Example

        Code:

        os.Setenv("NAME", "gopher")
        os.Setenv("BURROW", "/usr/gopher")
        
        fmt.Printf("%s lives in %s.\n", os.Getenv("NAME"), os.Getenv("BURROW"))
        
        

        Output:

        gopher lives in /usr/gopher.
        

        func Geteuid

        func Geteuid() int

        Geteuid returns the numeric effective user id of the caller.

        On Windows, it returns -1.

        func Getgid

        func Getgid() int

        Getgid returns the numeric group id of the caller.

        On Windows, it returns -1.

        func Getgroups

        func Getgroups() ([]int, error)

        Getgroups returns a list of the numeric ids of groups that the caller belongs to.

        On Windows, it returns syscall.EWINDOWS. See the os/user package for a possible alternative.

        func Getpagesize

        func Getpagesize() int

        Getpagesize returns the underlying system's memory page size.

        func Getpid

        func Getpid() int

        Getpid returns the process id of the caller.

        func Getppid

        func Getppid() int

        Getppid returns the process id of the caller's parent.

        func Getuid

        func Getuid() int

        Getuid returns the numeric user id of the caller.

        On Windows, it returns -1.

        func Getwd

        func Getwd() (dir string, err error)

        Getwd returns a rooted path name corresponding to the current directory. If the current directory can be reached via multiple paths (due to symbolic links), Getwd may return any one of them.

        func Hostname

        func Hostname() (name string, err error)

        Hostname returns the host name reported by the kernel.

        func IsExist

        func IsExist(err error) bool

        IsExist returns a boolean indicating whether the error is known to report that a file or directory already exists. It is satisfied by ErrExist as well as some syscall errors.

        This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrExist).

        func IsNotExist

        func IsNotExist(err error) bool

        IsNotExist returns a boolean indicating whether the error is known to report that a file or directory does not exist. It is satisfied by ErrNotExist as well as some syscall errors.

        This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrNotExist).

        func IsPathSeparator

        func IsPathSeparator(c uint8) bool

        IsPathSeparator reports whether c is a directory separator character.

        func IsPermission

        func IsPermission(err error) bool

        IsPermission returns a boolean indicating whether the error is known to report that permission is denied. It is satisfied by ErrPermission as well as some syscall errors.

        This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrPermission).

        func IsTimeout

        func IsTimeout(err error) bool

        IsTimeout returns a boolean indicating whether the error is known to report that a timeout occurred.

        This function predates errors.Is, and the notion of whether an error indicates a timeout can be ambiguous. For example, the Unix error EWOULDBLOCK sometimes indicates a timeout and sometimes does not. New code should use errors.Is with a value appropriate to the call returning the error, such as os.ErrDeadlineExceeded.

        func Lchown

        func Lchown(name string, uid, gid int) error

        Lchown changes the numeric uid and gid of the named file. If the file is a symbolic link, it changes the uid and gid of the link itself. If there is an error, it will be of type *PathError.

        On Windows, it always returns the syscall.EWINDOWS error, wrapped in *PathError.

        func Link(oldname, newname string) error

        Link creates newname as a hard link to the oldname file. If there is an error, it will be of type *LinkError.

        func LookupEnv

        func LookupEnv(key string) (string, bool)

        LookupEnv retrieves the value of the environment variable named by the key. If the variable is present in the environment the value (which may be empty) is returned and the boolean is true. Otherwise the returned value will be empty and the boolean will be false.

        Example

        Code:

        show := func(key string) {
            val, ok := os.LookupEnv(key)
            if !ok {
                fmt.Printf("%s not set\n", key)
            } else {
                fmt.Printf("%s=%s\n", key, val)
            }
        }
        
        os.Setenv("SOME_KEY", "value")
        os.Setenv("EMPTY_KEY", "")
        
        show("SOME_KEY")
        show("EMPTY_KEY")
        show("MISSING_KEY")
        
        

        Output:

        SOME_KEY=value
        EMPTY_KEY=
        MISSING_KEY not set
        

        func Mkdir

        func Mkdir(name string, perm FileMode) error

        Mkdir creates a new directory with the specified name and permission bits (before umask). If there is an error, it will be of type *PathError.

        Example

        Code:

        err := os.Mkdir("testdir", 0750)
        if err != nil && !os.IsExist(err) {
            log.Fatal(err)
        }
        err = os.WriteFile("testdir/testfile.txt", []byte("Hello, Gophers!"), 0660)
        if err != nil {
            log.Fatal(err)
        }
        

        func MkdirAll

        func MkdirAll(path string, perm FileMode) error

        MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm (before umask) are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

        Example

        Code:

        err := os.MkdirAll("test/subdir", 0750)
        if err != nil {
            log.Fatal(err)
        }
        err = os.WriteFile("test/subdir/testfile.txt", []byte("Hello, Gophers!"), 0660)
        if err != nil {
            log.Fatal(err)
        }
        

        func MkdirTemp

        func MkdirTemp(dir, pattern string) (string, error)

        MkdirTemp creates a new temporary directory in the directory dir and returns the pathname of the new directory. The new directory's name is generated by adding a random string to the end of pattern. If pattern includes a "*", the random string replaces the last "*" instead. If dir is the empty string, MkdirTemp uses the default directory for temporary files, as returned by TempDir. Multiple programs or goroutines calling MkdirTemp simultaneously will not choose the same directory. It is the caller's responsibility to remove the directory when it is no longer needed.

        Example

        Code:

        dir, err := os.MkdirTemp("", "example")
        if err != nil {
            log.Fatal(err)
        }
        defer os.RemoveAll(dir) // clean up
        
        file := filepath.Join(dir, "tmpfile")
        if err := os.WriteFile(file, []byte("content"), 0666); err != nil {
            log.Fatal(err)
        }
        

        Example (Suffix)

        Code:

        logsDir, err := os.MkdirTemp("", "*-logs")
        if err != nil {
            log.Fatal(err)
        }
        defer os.RemoveAll(logsDir) // clean up
        
        // Logs can be cleaned out earlier if needed by searching
        // for all directories whose suffix ends in *-logs.
        globPattern := filepath.Join(os.TempDir(), "*-logs")
        matches, err := filepath.Glob(globPattern)
        if err != nil {
            log.Fatalf("Failed to match %q: %v", globPattern, err)
        }
        
        for _, match := range matches {
            if err := os.RemoveAll(match); err != nil {
                log.Printf("Failed to remove %q: %v", match, err)
            }
        }
        

        func NewSyscallError

        func NewSyscallError(syscall string, err error) error

        NewSyscallError returns, as an error, a new SyscallError with the given system call name and error details. As a convenience, if err is nil, NewSyscallError returns nil.

        func Pipe

        func Pipe() (r *File, w *File, err error)

        Pipe returns a connected pair of Files; reads from r return bytes written to w. It returns the files and an error, if any.

        func ReadFile

        func ReadFile(name string) ([]byte, error)

        ReadFile reads the named file and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

        Example

        Code:

        data, err := os.ReadFile("testdata/hello")
        if err != nil {
            log.Fatal(err)
        }
        os.Stdout.Write(data)
        
        

        Output:

        Hello, Gophers!
        
        func Readlink(name string) (string, error)

        Readlink returns the destination of the named symbolic link. If there is an error, it will be of type *PathError.

        If the link destination is relative, Readlink returns the relative path without resolving it to an absolute one.

        func Remove

        func Remove(name string) error

        Remove removes the named file or (empty) directory. If there is an error, it will be of type *PathError.

        func RemoveAll

        func RemoveAll(path string) error

        RemoveAll removes path and any children it contains. It removes everything it can but returns the first error it encounters. If the path does not exist, RemoveAll returns nil (no error). If there is an error, it will be of type *PathError.

        func Rename

        func Rename(oldpath, newpath string) error

        Rename renames (moves) oldpath to newpath. If newpath already exists and is not a directory, Rename replaces it. OS-specific restrictions may apply when oldpath and newpath are in different directories. Even within the same directory, on non-Unix platforms Rename is not an atomic operation. If there is an error, it will be of type *LinkError.

        func SameFile

        func SameFile(fi1, fi2 FileInfo) bool

        SameFile reports whether fi1 and fi2 describe the same file. For example, on Unix this means that the device and inode fields of the two underlying structures are identical; on other systems the decision may be based on the path names. SameFile only applies to results returned by this package's Stat. It returns false in other cases.

        func Setenv

        func Setenv(key, value string) error

        Setenv sets the value of the environment variable named by the key. It returns an error, if any.

        func Symlink(oldname, newname string) error

        Symlink creates newname as a symbolic link to oldname. On Windows, a symlink to a non-existent oldname creates a file symlink; if oldname is later created as a directory the symlink will not work. If there is an error, it will be of type *LinkError.

        func TempDir

        func TempDir() string

        TempDir returns the default directory to use for temporary files.

        On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, it uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp.

        The directory is neither guaranteed to exist nor have accessible permissions.

        func Truncate

        func Truncate(name string, size int64) error

        Truncate changes the size of the named file. If the file is a symbolic link, it changes the size of the link's target. If there is an error, it will be of type *PathError.

        func Unsetenv

        func Unsetenv(key string) error

        Unsetenv unsets a single environment variable.

        Example

        Code:

        os.Setenv("TMPDIR", "/my/tmp")
        defer os.Unsetenv("TMPDIR")
        

        func UserCacheDir

        func UserCacheDir() (string, error)

        UserCacheDir returns the default root directory to use for user-specific cached data. Users should create their own application-specific subdirectory within this one and use that.

        On Unix systems, it returns $XDG_CACHE_HOME as specified by https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.cache. On Darwin, it returns $HOME/Library/Caches. On Windows, it returns %LocalAppData%. On Plan 9, it returns $home/lib/cache.

        If the location cannot be determined (for example, $HOME is not defined), then it will return an error.

        Example

        Code:

        dir, dirErr := os.UserCacheDir()
        if dirErr == nil {
            dir = filepath.Join(dir, "ExampleUserCacheDir")
        }
        
        getCache := func(name string) ([]byte, error) {
            if dirErr != nil {
                return nil, &os.PathError{Op: "getCache", Path: name, Err: os.ErrNotExist}
            }
            return os.ReadFile(filepath.Join(dir, name))
        }
        
        var mkdirOnce sync.Once
        putCache := func(name string, b []byte) error {
            if dirErr != nil {
                return &os.PathError{Op: "putCache", Path: name, Err: dirErr}
            }
            mkdirOnce.Do(func() {
                if err := os.MkdirAll(dir, 0700); err != nil {
                    log.Printf("can't create user cache dir: %v", err)
                }
            })
            return os.WriteFile(filepath.Join(dir, name), b, 0600)
        }
        
        // Read and store cached data.
        // …
        _ = getCache
        _ = putCache
        
        

        func UserConfigDir

        func UserConfigDir() (string, error)

        UserConfigDir returns the default root directory to use for user-specific configuration data. Users should create their own application-specific subdirectory within this one and use that.

        On Unix systems, it returns $XDG_CONFIG_HOME as specified by https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.config. On Darwin, it returns $HOME/Library/Application Support. On Windows, it returns %AppData%. On Plan 9, it returns $home/lib.

        If the location cannot be determined (for example, $HOME is not defined), then it will return an error.

        Example

        Code:

        dir, dirErr := os.UserConfigDir()
        
        var (
            configPath string
            origConfig []byte
        )
        if dirErr == nil {
            configPath = filepath.Join(dir, "ExampleUserConfigDir", "example.conf")
            var err error
            origConfig, err = os.ReadFile(configPath)
            if err != nil && !os.IsNotExist(err) {
                // The user has a config file but we couldn't read it.
                // Report the error instead of ignoring their configuration.
                log.Fatal(err)
            }
        }
        
        // Use and perhaps make changes to the config.
        config := bytes.Clone(origConfig)
        // …
        
        // Save changes.
        if !bytes.Equal(config, origConfig) {
            if configPath == "" {
                log.Printf("not saving config changes: %v", dirErr)
            } else {
                err := os.MkdirAll(filepath.Dir(configPath), 0700)
                if err == nil {
                    err = os.WriteFile(configPath, config, 0600)
                }
                if err != nil {
                    log.Printf("error saving config changes: %v", err)
                }
            }
        }
        
        

        func UserHomeDir

        func UserHomeDir() (string, error)

        UserHomeDir returns the current user's home directory.

        On Unix, including macOS, it returns the $HOME environment variable. On Windows, it returns %USERPROFILE%. On Plan 9, it returns the $home environment variable.

        If the expected variable is not set in the environment, UserHomeDir returns either a platform-specific default value or a non-nil error.

        func WriteFile

        func WriteFile(name string, data []byte, perm FileMode) error

        WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions. Since WriteFile requires multiple system calls to complete, a failure mid-operation can leave the file in a partially written state.

        Example

        Code:

        err := os.WriteFile("testdata/hello", []byte("Hello, Gophers!"), 0666)
        if err != nil {
            log.Fatal(err)
        }
        

        type DirEntry

        A DirEntry is an entry read from a directory (using the ReadDir function or a File's ReadDir method).

        type DirEntry = fs.DirEntry

        func ReadDir

        func ReadDir(name string) ([]DirEntry, error)

        ReadDir reads the named directory, returning all its directory entries sorted by filename. If an error occurs reading the directory, ReadDir returns the entries it was able to read before the error, along with the error.

        Example

        Code:

        files, err := os.ReadDir(".")
        if err != nil {
            log.Fatal(err)
        }
        
        for _, file := range files {
            fmt.Println(file.Name())
        }
        

        type File

        File represents an open file descriptor.

        type File struct {
            // contains filtered or unexported fields
        }
        

        func Create

        func Create(name string) (*File, error)

        Create creates or truncates the named file. If the file already exists, it is truncated. If the file does not exist, it is created with mode 0666 (before umask). If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR. If there is an error, it will be of type *PathError.

        func CreateTemp

        func CreateTemp(dir, pattern string) (*File, error)

        CreateTemp creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting file. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a "*", the random string replaces the last "*". If dir is the empty string, CreateTemp uses the default directory for temporary files, as returned by TempDir. Multiple programs or goroutines calling CreateTemp simultaneously will not choose the same file. The caller can use the file's Name method to find the pathname of the file. It is the caller's responsibility to remove the file when it is no longer needed.

        Example

        Code:

        f, err := os.CreateTemp("", "example")
        if err != nil {
            log.Fatal(err)
        }
        defer os.Remove(f.Name()) // clean up
        
        if _, err := f.Write([]byte("content")); err != nil {
            log.Fatal(err)
        }
        if err := f.Close(); err != nil {
            log.Fatal(err)
        }
        

        Example (Suffix)

        Code:

        f, err := os.CreateTemp("", "example.*.txt")
        if err != nil {
            log.Fatal(err)
        }
        defer os.Remove(f.Name()) // clean up
        
        if _, err := f.Write([]byte("content")); err != nil {
            f.Close()
            log.Fatal(err)
        }
        if err := f.Close(); err != nil {
            log.Fatal(err)
        }
        

        func NewFile

        func NewFile(fd uintptr, name string) *File

        NewFile returns a new File with the given file descriptor and name. The returned value will be nil if fd is not a valid file descriptor. On Unix systems, if the file descriptor is in non-blocking mode, NewFile will attempt to return a pollable File (one for which the SetDeadline methods work).

        After passing it to NewFile, fd may become invalid under the same conditions described in the comments of the Fd method, and the same constraints apply.

        func Open

        func Open(name string) (*File, error)

        Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

        func OpenFile

        func OpenFile(name string, flag int, perm FileMode) (*File, error)

        OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag is passed, it is created with mode perm (before umask). If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.

        Example

        Code:

        f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0644)
        if err != nil {
            log.Fatal(err)
        }
        if err := f.Close(); err != nil {
            log.Fatal(err)
        }
        

        Example (Append)

        Code:

        // If the file doesn't exist, create it, or append to the file
        f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
        if err != nil {
            log.Fatal(err)
        }
        if _, err := f.Write([]byte("appended some data\n")); err != nil {
            f.Close() // ignore error; Write error takes precedence
            log.Fatal(err)
        }
        if err := f.Close(); err != nil {
            log.Fatal(err)
        }
        

        func (*File) Chdir

        func (f *File) Chdir() error

        Chdir changes the current working directory to the file, which must be a directory. If there is an error, it will be of type *PathError.

        func (*File) Chmod

        func (f *File) Chmod(mode FileMode) error

        Chmod changes the mode of the file to mode. If there is an error, it will be of type *PathError.

        func (*File) Chown

        func (f *File) Chown(uid, gid int) error

        Chown changes the numeric uid and gid of the named file. If there is an error, it will be of type *PathError.

        On Windows, it always returns the syscall.EWINDOWS error, wrapped in *PathError.

        func (*File) Close

        func (f *File) Close() error

        Close closes the File, rendering it unusable for I/O. On files that support SetDeadline, any pending I/O operations will be canceled and return immediately with an ErrClosed error. Close will return an error if it has already been called.

        func (*File) Fd

        func (f *File) Fd() uintptr

        Fd returns the integer Unix file descriptor referencing the open file. If f is closed, the file descriptor becomes invalid. If f is garbage collected, a finalizer may close the file descriptor, making it invalid; see runtime.SetFinalizer for more information on when a finalizer might be run. On Unix systems this will cause the SetDeadline methods to stop working. Because file descriptors can be reused, the returned file descriptor may only be closed through the Close method of f, or by its finalizer during garbage collection. Otherwise, during garbage collection the finalizer may close an unrelated file descriptor with the same (reused) number.

        As an alternative, see the f.SyscallConn method.

        func (*File) Name

        func (f *File) Name() string

        Name returns the name of the file as presented to Open.

        func (*File) Read

        func (f *File) Read(b []byte) (n int, err error)

        Read reads up to len(b) bytes from the File and stores them in b. It returns the number of bytes read and any error encountered. At end of file, Read returns 0, io.EOF.

        func (*File) ReadAt

        func (f *File) ReadAt(b []byte, off int64) (n int, err error)

        ReadAt reads len(b) bytes from the File starting at byte offset off. It returns the number of bytes read and the error, if any. ReadAt always returns a non-nil error when n < len(b). At end of file, that error is io.EOF.

        func (*File) ReadDir

        func (f *File) ReadDir(n int) ([]DirEntry, error)

        ReadDir reads the contents of the directory associated with the file f and returns a slice of DirEntry values in directory order. Subsequent calls on the same file will yield later DirEntry records in the directory.

        If n > 0, ReadDir returns at most n DirEntry records. In this case, if ReadDir returns an empty slice, it will return an error explaining why. At the end of a directory, the error is io.EOF.

        If n <= 0, ReadDir returns all the DirEntry records remaining in the directory. When it succeeds, it returns a nil error (not io.EOF).

        func (*File) ReadFrom

        func (f *File) ReadFrom(r io.Reader) (n int64, err error)

        ReadFrom implements io.ReaderFrom.

        func (*File) Readdir

        func (f *File) Readdir(n int) ([]FileInfo, error)

        Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.

        If n > 0, Readdir returns at most n FileInfo structures. In this case, if Readdir returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is io.EOF.

        If n <= 0, Readdir returns all the FileInfo from the directory in a single slice. In this case, if Readdir succeeds (reads all the way to the end of the directory), it returns the slice and a nil error. If it encounters an error before the end of the directory, Readdir returns the FileInfo read until that point and a non-nil error.

        Most clients are better served by the more efficient ReadDir method.

        func (*File) Readdirnames

        func (f *File) Readdirnames(n int) (names []string, err error)

        Readdirnames reads the contents of the directory associated with file and returns a slice of up to n names of files in the directory, in directory order. Subsequent calls on the same file will yield further names.

        If n > 0, Readdirnames returns at most n names. In this case, if Readdirnames returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is io.EOF.

        If n <= 0, Readdirnames returns all the names from the directory in a single slice. In this case, if Readdirnames succeeds (reads all the way to the end of the directory), it returns the slice and a nil error. If it encounters an error before the end of the directory, Readdirnames returns the names read until that point and a non-nil error.

        func (*File) Seek

        func (f *File) Seek(offset int64, whence int) (ret int64, err error)

        Seek sets the offset for the next Read or Write on file to offset, interpreted according to whence: 0 means relative to the origin of the file, 1 means relative to the current offset, and 2 means relative to the end. It returns the new offset and an error, if any. The behavior of Seek on a file opened with O_APPEND is not specified.

        func (*File) SetDeadline

        func (f *File) SetDeadline(t time.Time) error

        SetDeadline sets the read and write deadlines for a File. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.

        Only some kinds of files support setting a deadline. Calls to SetDeadline for files that do not support deadlines will return ErrNoDeadline. On most systems ordinary files do not support deadlines, but pipes do.

        A deadline is an absolute time after which I/O operations fail with an error instead of blocking. The deadline applies to all future and pending I/O, not just the immediately following call to Read or Write. After a deadline has been exceeded, the connection can be refreshed by setting a deadline in the future.

        If the deadline is exceeded a call to Read or Write or to other I/O methods will return an error that wraps ErrDeadlineExceeded. This can be tested using errors.Is(err, os.ErrDeadlineExceeded). That error implements the Timeout method, and calling the Timeout method will return true, but there are other possible errors for which the Timeout will return true even if the deadline has not been exceeded.

        An idle timeout can be implemented by repeatedly extending the deadline after successful Read or Write calls.

        A zero value for t means I/O operations will not time out.

        func (*File) SetReadDeadline

        func (f *File) SetReadDeadline(t time.Time) error

        SetReadDeadline sets the deadline for future Read calls and any currently-blocked Read call. A zero value for t means Read will not time out. Not all files support setting deadlines; see SetDeadline.

        func (*File) SetWriteDeadline

        func (f *File) SetWriteDeadline(t time.Time) error

        SetWriteDeadline sets the deadline for any future Write calls and any currently-blocked Write call. Even if Write times out, it may return n > 0, indicating that some of the data was successfully written. A zero value for t means Write will not time out. Not all files support setting deadlines; see SetDeadline.

        func (*File) Stat

        func (f *File) Stat() (FileInfo, error)

        Stat returns the FileInfo structure describing file. If there is an error, it will be of type *PathError.

        func (*File) Sync

        func (f *File) Sync() error

        Sync commits the current contents of the file to stable storage. Typically, this means flushing the file system's in-memory copy of recently written data to disk.

        func (*File) SyscallConn

        func (f *File) SyscallConn() (syscall.RawConn, error)

        SyscallConn returns a raw file. This implements the syscall.Conn interface.

        func (*File) Truncate

        func (f *File) Truncate(size int64) error

        Truncate changes the size of the file. It does not change the I/O offset. If there is an error, it will be of type *PathError.

        func (*File) Write

        func (f *File) Write(b []byte) (n int, err error)

        Write writes len(b) bytes from b to the File. It returns the number of bytes written and an error, if any. Write returns a non-nil error when n != len(b).

        func (*File) WriteAt

        func (f *File) WriteAt(b []byte, off int64) (n int, err error)

        WriteAt writes len(b) bytes to the File starting at byte offset off. It returns the number of bytes written and an error, if any. WriteAt returns a non-nil error when n != len(b).

        If file was opened with the O_APPEND flag, WriteAt returns an error.

        func (*File) WriteString

        func (f *File) WriteString(s string) (n int, err error)

        WriteString is like Write, but writes the contents of string s rather than a slice of bytes.

        func (*File) WriteTo

        func (f *File) WriteTo(w io.Writer) (n int64, err error)

        WriteTo implements io.WriterTo.

        type FileInfo

        A FileInfo describes a file and is returned by Stat and Lstat.

        type FileInfo = fs.FileInfo

        func Lstat

        func Lstat(name string) (FileInfo, error)

        Lstat returns a FileInfo describing the named file. If the file is a symbolic link, the returned FileInfo describes the symbolic link. Lstat makes no attempt to follow the link. If there is an error, it will be of type *PathError.

        On Windows, if the file is a reparse point that is a surrogate for another named entity (such as a symbolic link or mounted folder), the returned FileInfo describes the reparse point, and makes no attempt to resolve it.

        func Stat

        func Stat(name string) (FileInfo, error)

        Stat returns a FileInfo describing the named file. If there is an error, it will be of type *PathError.

        type FileMode

        A FileMode represents a file's mode and permission bits. The bits have the same definition on all systems, so that information about files can be moved from one system to another portably. Not all bits apply to all systems. The only required bit is ModeDir for directories.

        type FileMode = fs.FileMode

        Example

        Code:

        fi, err := os.Lstat("some-filename")
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("permissions: %#o\n", fi.Mode().Perm()) // 0400, 0777, etc.
        switch mode := fi.Mode(); {
        case mode.IsRegular():
            fmt.Println("regular file")
        case mode.IsDir():
            fmt.Println("directory")
        case mode&fs.ModeSymlink != 0:
            fmt.Println("symbolic link")
        case mode&fs.ModeNamedPipe != 0:
            fmt.Println("named pipe")
        }
        

        type LinkError

        LinkError records an error during a link or symlink or rename system call and the paths that caused it.

        type LinkError struct {
            Op  string
            Old string
            New string
            Err error
        }
        

        func (*LinkError) Error

        func (e *LinkError) Error() string

        func (*LinkError) Unwrap

        func (e *LinkError) Unwrap() error

        type PathError

        PathError records an error and the operation and file path that caused it.

        type PathError = fs.PathError

        type ProcAttr

        ProcAttr holds the attributes that will be applied to a new process started by StartProcess.

        type ProcAttr struct {
            // If Dir is non-empty, the child changes into the directory before
            // creating the process.
            Dir string
            // If Env is non-nil, it gives the environment variables for the
            // new process in the form returned by Environ.
            // If it is nil, the result of Environ will be used.
            Env []string
            // Files specifies the open files inherited by the new process. The
            // first three entries correspond to standard input, standard output, and
            // standard error. An implementation may support additional entries,
            // depending on the underlying operating system. A nil entry corresponds
            // to that file being closed when the process starts.
            // On Unix systems, StartProcess will change these File values
            // to blocking mode, which means that SetDeadline will stop working
            // and calling Close will not interrupt a Read or Write.
            Files []*File
        
            // Operating system-specific process creation attributes.
            // Note that setting this field means that your program
            // may not execute properly or even compile on some
            // operating systems.
            Sys *syscall.SysProcAttr
        }
        

        type Process

        Process stores the information about a process created by StartProcess.

        type Process struct {
            Pid int
            // contains filtered or unexported fields
        }
        

        func FindProcess

        func FindProcess(pid int) (*Process, error)

        FindProcess looks for a running process by its pid.

        The Process it returns can be used to obtain information about the underlying operating system process.

        On Unix systems, FindProcess always succeeds and returns a Process for the given pid, regardless of whether the process exists. To test whether the process actually exists, see whether p.Signal(syscall.Signal(0)) reports an error.

        func StartProcess

        func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)

        StartProcess starts a new process with the program, arguments and attributes specified by name, argv and attr. The argv slice will become os.Args in the new process, so it normally starts with the program name.

        If the calling goroutine has locked the operating system thread with runtime.LockOSThread and modified any inheritable OS-level thread state (for example, Linux or Plan 9 name spaces), the new process will inherit the caller's thread state.

        StartProcess is a low-level interface. The os/exec package provides higher-level interfaces.

        If there is an error, it will be of type *PathError.

        func (*Process) Kill

        func (p *Process) Kill() error

        Kill causes the Process to exit immediately. Kill does not wait until the Process has actually exited. This only kills the Process itself, not any other processes it may have started.

        func (*Process) Release

        func (p *Process) Release() error

        Release releases any resources associated with the Process p, rendering it unusable in the future. Release only needs to be called if Wait is not.

        func (*Process) Signal

        func (p *Process) Signal(sig Signal) error

        Signal sends a signal to the Process. Sending Interrupt on Windows is not implemented.

        func (*Process) Wait

        func (p *Process) Wait() (*ProcessState, error)

        Wait waits for the Process to exit, and then returns a ProcessState describing its status and an error, if any. Wait releases any resources associated with the Process. On most operating systems, the Process must be a child of the current process or an error will be returned.

        type ProcessState

        ProcessState stores information about a process, as reported by Wait.

        type ProcessState struct {
            // contains filtered or unexported fields
        }
        

        func (*ProcessState) ExitCode

        func (p *ProcessState) ExitCode() int

        ExitCode returns the exit code of the exited process, or -1 if the process hasn't exited or was terminated by a signal.

        func (*ProcessState) Exited

        func (p *ProcessState) Exited() bool

        Exited reports whether the program has exited. On Unix systems this reports true if the program exited due to calling exit, but false if the program terminated due to a signal.

        func (*ProcessState) Pid

        func (p *ProcessState) Pid() int

        Pid returns the process id of the exited process.

        func (*ProcessState) String

        func (p *ProcessState) String() string

        func (*ProcessState) Success

        func (p *ProcessState) Success() bool

        Success reports whether the program exited successfully, such as with exit status 0 on Unix.

        func (*ProcessState) Sys

        func (p *ProcessState) Sys() any

        Sys returns system-dependent exit information about the process. Convert it to the appropriate underlying type, such as syscall.WaitStatus on Unix, to access its contents.

        func (*ProcessState) SysUsage

        func (p *ProcessState) SysUsage() any

        SysUsage returns system-dependent resource usage information about the exited process. Convert it to the appropriate underlying type, such as *syscall.Rusage on Unix, to access its contents. (On Unix, *syscall.Rusage matches struct rusage as defined in the getrusage(2) manual page.)

        func (*ProcessState) SystemTime

        func (p *ProcessState) SystemTime() time.Duration

        SystemTime returns the system CPU time of the exited process and its children.

        func (*ProcessState) UserTime

        func (p *ProcessState) UserTime() time.Duration

        UserTime returns the user CPU time of the exited process and its children.

        type Signal

        A Signal represents an operating system signal. The usual underlying implementation is operating system-dependent: on Unix it is syscall.Signal.

        type Signal interface {
            String() string
            Signal() // to distinguish from other Stringers
        }

        The only signal values guaranteed to be present in the os package on all systems are os.Interrupt (send the process an interrupt) and os.Kill (force the process to exit). On Windows, sending os.Interrupt to a process with os.Process.Signal is not implemented; it will return an error instead of sending a signal.

        var (
            Interrupt Signal = syscall.SIGINT
            Kill      Signal = syscall.SIGKILL
        )

        type SyscallError

        SyscallError records an error from a specific system call.

        type SyscallError struct {
            Syscall string
            Err     error
        }
        

        func (*SyscallError) Error

        func (e *SyscallError) Error() string

        func (*SyscallError) Timeout

        func (e *SyscallError) Timeout() bool

        Timeout reports whether this error represents a timeout.

        func (*SyscallError) Unwrap

        func (e *SyscallError) Unwrap() error

        Subdirectories

        Name Synopsis
        ..
        exec Package exec runs external commands.
        signal Package signal implements access to incoming signals.
        user Package user allows user account lookups by name or id.
        exec - Go Documentation Server
        ...

        Package exec

        Overview ▾

        Package exec runs external commands. It wraps os.StartProcess to make it easier to remap stdin and stdout, connect I/O with pipes, and do other adjustments.

        Unlike the "system" library call from C and other languages, the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells. The package behaves more like C's "exec" family of functions. To expand glob patterns, either call the shell directly, taking care to escape any dangerous input, or use the path/filepath package's Glob function. To expand environment variables, use package os's ExpandEnv.

        Note that the examples in this package assume a Unix system. They may not run on Windows, and they do not run in the Go Playground used by golang.org and godoc.org.

        Executables in the current directory

        The functions Command and LookPath look for a program in the directories listed in the current path, following the conventions of the host operating system. Operating systems have for decades included the current directory in this search, sometimes implicitly and sometimes configured explicitly that way by default. Modern practice is that including the current directory is usually unexpected and often leads to security problems.

        To avoid those security problems, as of Go 1.19, this package will not resolve a program using an implicit or explicit path entry relative to the current directory. That is, if you run exec.LookPath("go"), it will not successfully return ./go on Unix nor .\go.exe on Windows, no matter how the path is configured. Instead, if the usual path algorithms would result in that answer, these functions return an error err satisfying errors.Is(err, ErrDot).

        For example, consider these two program snippets:

        path, err := exec.LookPath("prog")
        if err != nil {
        	log.Fatal(err)
        }
        use(path)
        

        and

        cmd := exec.Command("prog")
        if err := cmd.Run(); err != nil {
        	log.Fatal(err)
        }
        

        These will not find and run ./prog or .\prog.exe, no matter how the current path is configured.

        Code that always wants to run a program from the current directory can be rewritten to say "./prog" instead of "prog".

        Code that insists on including results from relative path entries can instead override the error using an errors.Is check:

        path, err := exec.LookPath("prog")
        if errors.Is(err, exec.ErrDot) {
        	err = nil
        }
        if err != nil {
        	log.Fatal(err)
        }
        use(path)
        

        and

        cmd := exec.Command("prog")
        if errors.Is(cmd.Err, exec.ErrDot) {
        	cmd.Err = nil
        }
        if err := cmd.Run(); err != nil {
        	log.Fatal(err)
        }
        

        Setting the environment variable GODEBUG=execerrdot=0 disables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19 behavior for programs that are unable to apply more targeted fixes. A future version of Go may remove support for this variable.

        Before adding such overrides, make sure you understand the security implications of doing so. See https://go.dev/blog/path-security for more information.

        Variables

        ErrDot indicates that a path lookup resolved to an executable in the current directory due to ‘.’ being in the path, either implicitly or explicitly. See the package documentation for details.

        Note that functions in this package do not return ErrDot directly. Code should use errors.Is(err, ErrDot), not err == ErrDot, to test whether a returned error err is due to this condition.

        var ErrDot = errors.New("cannot run executable found relative to current directory")

        ErrNotFound is the error resulting if a path search failed to find an executable file.

        var ErrNotFound = errors.New("executable file not found in $PATH")

        ErrWaitDelay is returned by (*Cmd).Wait if the process exits with a successful status code but its output pipes are not closed before the command's WaitDelay expires.

        var ErrWaitDelay = errors.New("exec: WaitDelay expired before I/O complete")

        func LookPath

        func LookPath(file string) (string, error)

        LookPath searches for an executable named file in the directories named by the PATH environment variable. If file contains a slash, it is tried directly and the PATH is not consulted. Otherwise, on success, the result is an absolute path.

        In older versions of Go, LookPath could return a path relative to the current directory. As of Go 1.19, LookPath will instead return that path along with an error satisfying errors.Is(err, ErrDot). See the package documentation for more details.

        Example

        Code:

        path, err := exec.LookPath("fortune")
        if err != nil {
            log.Fatal("installing fortune is in your future")
        }
        fmt.Printf("fortune is available at %s\n", path)
        

        type Cmd

        Cmd represents an external command being prepared or run.

        A Cmd cannot be reused after calling its Run, Output or CombinedOutput methods.

        type Cmd struct {
            // Path is the path of the command to run.
            //
            // This is the only field that must be set to a non-zero
            // value. If Path is relative, it is evaluated relative
            // to Dir.
            Path string
        
            // Args holds command line arguments, including the command as Args[0].
            // If the Args field is empty or nil, Run uses {Path}.
            //
            // In typical use, both Path and Args are set by calling Command.
            Args []string
        
            // Env specifies the environment of the process.
            // Each entry is of the form "key=value".
            // If Env is nil, the new process uses the current process's
            // environment.
            // If Env contains duplicate environment keys, only the last
            // value in the slice for each duplicate key is used.
            // As a special case on Windows, SYSTEMROOT is always added if
            // missing and not explicitly set to the empty string.
            Env []string
        
            // Dir specifies the working directory of the command.
            // If Dir is the empty string, Run runs the command in the
            // calling process's current directory.
            Dir string
        
            // Stdin specifies the process's standard input.
            //
            // If Stdin is nil, the process reads from the null device (os.DevNull).
            //
            // If Stdin is an *os.File, the process's standard input is connected
            // directly to that file.
            //
            // Otherwise, during the execution of the command a separate
            // goroutine reads from Stdin and delivers that data to the command
            // over a pipe. In this case, Wait does not complete until the goroutine
            // stops copying, either because it has reached the end of Stdin
            // (EOF or a read error), or because writing to the pipe returned an error,
            // or because a nonzero WaitDelay was set and expired.
            Stdin io.Reader
        
            // Stdout and Stderr specify the process's standard output and error.
            //
            // If either is nil, Run connects the corresponding file descriptor
            // to the null device (os.DevNull).
            //
            // If either is an *os.File, the corresponding output from the process
            // is connected directly to that file.
            //
            // Otherwise, during the execution of the command a separate goroutine
            // reads from the process over a pipe and delivers that data to the
            // corresponding Writer. In this case, Wait does not complete until the
            // goroutine reaches EOF or encounters an error or a nonzero WaitDelay
            // expires.
            //
            // If Stdout and Stderr are the same writer, and have a type that can
            // be compared with ==, at most one goroutine at a time will call Write.
            Stdout io.Writer
            Stderr io.Writer
        
            // ExtraFiles specifies additional open files to be inherited by the
            // new process. It does not include standard input, standard output, or
            // standard error. If non-nil, entry i becomes file descriptor 3+i.
            //
            // ExtraFiles is not supported on Windows.
            ExtraFiles []*os.File
        
            // SysProcAttr holds optional, operating system-specific attributes.
            // Run passes it to os.StartProcess as the os.ProcAttr's Sys field.
            SysProcAttr *syscall.SysProcAttr
        
            // Process is the underlying process, once started.
            Process *os.Process
        
            // ProcessState contains information about an exited process.
            // If the process was started successfully, Wait or Run will
            // populate its ProcessState when the command completes.
            ProcessState *os.ProcessState
        
            Err error // LookPath error, if any.
        
            // If Cancel is non-nil, the command must have been created with
            // CommandContext and Cancel will be called when the command's
            // Context is done. By default, CommandContext sets Cancel to
            // call the Kill method on the command's Process.
            //
            // Typically a custom Cancel will send a signal to the command's
            // Process, but it may instead take other actions to initiate cancellation,
            // such as closing a stdin or stdout pipe or sending a shutdown request on a
            // network socket.
            //
            // If the command exits with a success status after Cancel is
            // called, and Cancel does not return an error equivalent to
            // os.ErrProcessDone, then Wait and similar methods will return a non-nil
            // error: either an error wrapping the one returned by Cancel,
            // or the error from the Context.
            // (If the command exits with a non-success status, or Cancel
            // returns an error that wraps os.ErrProcessDone, Wait and similar methods
            // continue to return the command's usual exit status.)
            //
            // If Cancel is set to nil, nothing will happen immediately when the command's
            // Context is done, but a nonzero WaitDelay will still take effect. That may
            // be useful, for example, to work around deadlocks in commands that do not
            // support shutdown signals but are expected to always finish quickly.
            //
            // Cancel will not be called if Start returns a non-nil error.
            Cancel func() error
        
            // If WaitDelay is non-zero, it bounds the time spent waiting on two sources
            // of unexpected delay in Wait: a child process that fails to exit after the
            // associated Context is canceled, and a child process that exits but leaves
            // its I/O pipes unclosed.
            //
            // The WaitDelay timer starts when either the associated Context is done or a
            // call to Wait observes that the child process has exited, whichever occurs
            // first. When the delay has elapsed, the command shuts down the child process
            // and/or its I/O pipes.
            //
            // If the child process has failed to exit — perhaps because it ignored or
            // failed to receive a shutdown signal from a Cancel function, or because no
            // Cancel function was set — then it will be terminated using os.Process.Kill.
            //
            // Then, if the I/O pipes communicating with the child process are still open,
            // those pipes are closed in order to unblock any goroutines currently blocked
            // on Read or Write calls.
            //
            // If pipes are closed due to WaitDelay, no Cancel call has occurred,
            // and the command has otherwise exited with a successful status, Wait and
            // similar methods will return ErrWaitDelay instead of nil.
            //
            // If WaitDelay is zero (the default), I/O pipes will be read until EOF,
            // which might not occur until orphaned subprocesses of the command have
            // also closed their descriptors for the pipes.
            WaitDelay time.Duration
            // contains filtered or unexported fields
        }
        

        func Command

        func Command(name string, arg ...string) *Cmd

        Command returns the Cmd struct to execute the named program with the given arguments.

        It sets only the Path and Args in the returned structure.

        If name contains no path separators, Command uses LookPath to resolve name to a complete path if possible. Otherwise it uses name directly as Path.

        The returned Cmd's Args field is constructed from the command name followed by the elements of arg, so arg should not include the command name itself. For example, Command("echo", "hello"). Args[0] is always name, not the possibly resolved Path.

        On Windows, processes receive the whole command line as a single string and do their own parsing. Command combines and quotes Args into a command line string with an algorithm compatible with applications using CommandLineToArgvW (which is the most common way). Notable exceptions are msiexec.exe and cmd.exe (and thus, all batch files), which have a different unquoting algorithm. In these or other similar cases, you can do the quoting yourself and provide the full command line in SysProcAttr.CmdLine, leaving Args empty.

        Example

        Code:

        cmd := exec.Command("tr", "a-z", "A-Z")
        cmd.Stdin = strings.NewReader("some input")
        var out strings.Builder
        cmd.Stdout = &out
        err := cmd.Run()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("in all caps: %q\n", out.String())
        

        Example (Environment)

        Code:

        cmd := exec.Command("prog")
        cmd.Env = append(os.Environ(),
            "FOO=duplicate_value", // ignored
            "FOO=actual_value",    // this value is used
        )
        if err := cmd.Run(); err != nil {
            log.Fatal(err)
        }
        

        func CommandContext

        func CommandContext(ctx context.Context, name string, arg ...string) *Cmd

        CommandContext is like Command but includes a context.

        The provided context is used to interrupt the process (by calling cmd.Cancel or os.Process.Kill) if the context becomes done before the command completes on its own.

        CommandContext sets the command's Cancel function to invoke the Kill method on its Process, and leaves its WaitDelay unset. The caller may change the cancellation behavior by modifying those fields before starting the command.

        Example

        Code:

        ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
        defer cancel()
        
        if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
            // This will fail after 100 milliseconds. The 5 second sleep
            // will be interrupted.
        }
        

        func (*Cmd) CombinedOutput

        func (c *Cmd) CombinedOutput() ([]byte, error)

        CombinedOutput runs the command and returns its combined standard output and standard error.

        Example

        Code:

        cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr")
        stdoutStderr, err := cmd.CombinedOutput()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s\n", stdoutStderr)
        

        func (*Cmd) Environ

        func (c *Cmd) Environ() []string

        Environ returns a copy of the environment in which the command would be run as it is currently configured.

        Example

        Code:

        cmd := exec.Command("pwd")
        
        // Set Dir before calling cmd.Environ so that it will include an
        // updated PWD variable (on platforms where that is used).
        cmd.Dir = ".."
        cmd.Env = append(cmd.Environ(), "POSIXLY_CORRECT=1")
        
        out, err := cmd.Output()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s\n", out)
        

        func (*Cmd) Output

        func (c *Cmd) Output() ([]byte, error)

        Output runs the command and returns its standard output. Any returned error will usually be of type *ExitError. If c.Stderr was nil, Output populates ExitError.Stderr.

        Example

        Code:

        out, err := exec.Command("date").Output()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("The date is %s\n", out)
        

        func (*Cmd) Run

        func (c *Cmd) Run() error

        Run starts the specified command and waits for it to complete.

        The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

        If the command starts but does not complete successfully, the error is of type *ExitError. Other error types may be returned for other situations.

        If the calling goroutine has locked the operating system thread with runtime.LockOSThread and modified any inheritable OS-level thread state (for example, Linux or Plan 9 name spaces), the new process will inherit the caller's thread state.

        Example

        Code:

        cmd := exec.Command("sleep", "1")
        log.Printf("Running command and waiting for it to finish...")
        err := cmd.Run()
        log.Printf("Command finished with error: %v", err)
        

        func (*Cmd) Start

        func (c *Cmd) Start() error

        Start starts the specified command but does not wait for it to complete.

        If Start returns successfully, the c.Process field will be set.

        After a successful call to Start the Wait method must be called in order to release associated system resources.

        Example

        Code:

        cmd := exec.Command("sleep", "5")
        err := cmd.Start()
        if err != nil {
            log.Fatal(err)
        }
        log.Printf("Waiting for command to finish...")
        err = cmd.Wait()
        log.Printf("Command finished with error: %v", err)
        

        func (*Cmd) StderrPipe

        func (c *Cmd) StderrPipe() (io.ReadCloser, error)

        StderrPipe returns a pipe that will be connected to the command's standard error when the command starts.

        Wait will close the pipe after seeing the command exit, so most callers need not close the pipe themselves. It is thus incorrect to call Wait before all reads from the pipe have completed. For the same reason, it is incorrect to use Run when using StderrPipe. See the StdoutPipe example for idiomatic usage.

        Example

        Code:

        cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr")
        stderr, err := cmd.StderrPipe()
        if err != nil {
            log.Fatal(err)
        }
        
        if err := cmd.Start(); err != nil {
            log.Fatal(err)
        }
        
        slurp, _ := io.ReadAll(stderr)
        fmt.Printf("%s\n", slurp)
        
        if err := cmd.Wait(); err != nil {
            log.Fatal(err)
        }
        

        func (*Cmd) StdinPipe

        func (c *Cmd) StdinPipe() (io.WriteCloser, error)

        StdinPipe returns a pipe that will be connected to the command's standard input when the command starts. The pipe will be closed automatically after Wait sees the command exit. A caller need only call Close to force the pipe to close sooner. For example, if the command being run will not exit until standard input is closed, the caller must close the pipe.

        Example

        Code:

        cmd := exec.Command("cat")
        stdin, err := cmd.StdinPipe()
        if err != nil {
            log.Fatal(err)
        }
        
        go func() {
            defer stdin.Close()
            io.WriteString(stdin, "values written to stdin are passed to cmd's standard input")
        }()
        
        out, err := cmd.CombinedOutput()
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Printf("%s\n", out)
        

        func (*Cmd) StdoutPipe

        func (c *Cmd) StdoutPipe() (io.ReadCloser, error)

        StdoutPipe returns a pipe that will be connected to the command's standard output when the command starts.

        Wait will close the pipe after seeing the command exit, so most callers need not close the pipe themselves. It is thus incorrect to call Wait before all reads from the pipe have completed. For the same reason, it is incorrect to call Run when using StdoutPipe. See the example for idiomatic usage.

        Example

        Code:

        cmd := exec.Command("echo", "-n", `{"Name": "Bob", "Age": 32}`)
        stdout, err := cmd.StdoutPipe()
        if err != nil {
            log.Fatal(err)
        }
        if err := cmd.Start(); err != nil {
            log.Fatal(err)
        }
        var person struct {
            Name string
            Age  int
        }
        if err := json.NewDecoder(stdout).Decode(&person); err != nil {
            log.Fatal(err)
        }
        if err := cmd.Wait(); err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s is %d years old\n", person.Name, person.Age)
        

        func (*Cmd) String

        func (c *Cmd) String() string

        String returns a human-readable description of c. It is intended only for debugging. In particular, it is not suitable for use as input to a shell. The output of String may vary across Go releases.

        func (*Cmd) Wait

        func (c *Cmd) Wait() error

        Wait waits for the command to exit and waits for any copying to stdin or copying from stdout or stderr to complete.

        The command must have been started by Start.

        The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

        If the command fails to run or doesn't complete successfully, the error is of type *ExitError. Other error types may be returned for I/O problems.

        If any of c.Stdin, c.Stdout or c.Stderr are not an *os.File, Wait also waits for the respective I/O loop copying to or from the process to complete.

        Wait releases any resources associated with the Cmd.

        type Error

        Error is returned by LookPath when it fails to classify a file as an executable.

        type Error struct {
            // Name is the file name for which the error occurred.
            Name string
            // Err is the underlying error.
            Err error
        }
        

        func (*Error) Error

        func (e *Error) Error() string

        func (*Error) Unwrap

        func (e *Error) Unwrap() error

        type ExitError

        An ExitError reports an unsuccessful exit by a command.

        type ExitError struct {
            *os.ProcessState
        
            // Stderr holds a subset of the standard error output from the
            // Cmd.Output method if standard error was not otherwise being
            // collected.
            //
            // If the error output is long, Stderr may contain only a prefix
            // and suffix of the output, with the middle replaced with
            // text about the number of omitted bytes.
            //
            // Stderr is provided for debugging, for inclusion in error messages.
            // Users with other needs should redirect Cmd.Stderr as needed.
            Stderr []byte
        }
        

        func (*ExitError) Error

        func (e *ExitError) Error() string

        Subdirectories

        Name Synopsis
        ..
        signal - Go Documentation Server
        ...

        Package signal

        import "os/signal"
        Overview
        Index
        Examples

        Overview ▾

        Package signal implements access to incoming signals.

        Signals are primarily used on Unix-like systems. For the use of this package on Windows and Plan 9, see below.

        Types of signals

        The signals SIGKILL and SIGSTOP may not be caught by a program, and therefore cannot be affected by this package.

        Synchronous signals are signals triggered by errors in program execution: SIGBUS, SIGFPE, and SIGSEGV. These are only considered synchronous when caused by program execution, not when sent using os.Process.Kill or the kill program or some similar mechanism. In general, except as discussed below, Go programs will convert a synchronous signal into a run-time panic.

        The remaining signals are asynchronous signals. They are not triggered by program errors, but are instead sent from the kernel or from some other program.

        Of the asynchronous signals, the SIGHUP signal is sent when a program loses its controlling terminal. The SIGINT signal is sent when the user at the controlling terminal presses the interrupt character, which by default is ^C (Control-C). The SIGQUIT signal is sent when the user at the controlling terminal presses the quit character, which by default is ^\ (Control-Backslash). In general you can cause a program to simply exit by pressing ^C, and you can cause it to exit with a stack dump by pressing ^\.

        Default behavior of signals in Go programs

        By default, a synchronous signal is converted into a run-time panic. A SIGHUP, SIGINT, or SIGTERM signal causes the program to exit. A SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGSTKFLT, SIGEMT, or SIGSYS signal causes the program to exit with a stack dump. A SIGTSTP, SIGTTIN, or SIGTTOU signal gets the system default behavior (these signals are used by the shell for job control). The SIGPROF signal is handled directly by the Go runtime to implement runtime.CPUProfile. Other signals will be caught but no action will be taken.

        If the Go program is started with either SIGHUP or SIGINT ignored (signal handler set to SIG_IGN), they will remain ignored.

        If the Go program is started with a non-empty signal mask, that will generally be honored. However, some signals are explicitly unblocked: the synchronous signals, SIGILL, SIGTRAP, SIGSTKFLT, SIGCHLD, SIGPROF, and, on Linux, signals 32 (SIGCANCEL) and 33 (SIGSETXID) (SIGCANCEL and SIGSETXID are used internally by glibc). Subprocesses started by os.Exec, or by os/exec, will inherit the modified signal mask.

        Changing the behavior of signals in Go programs

        The functions in this package allow a program to change the way Go programs handle signals.

        Notify disables the default behavior for a given set of asynchronous signals and instead delivers them over one or more registered channels. Specifically, it applies to the signals SIGHUP, SIGINT, SIGQUIT, SIGABRT, and SIGTERM. It also applies to the job control signals SIGTSTP, SIGTTIN, and SIGTTOU, in which case the system default behavior does not occur. It also applies to some signals that otherwise cause no action: SIGUSR1, SIGUSR2, SIGPIPE, SIGALRM, SIGCHLD, SIGCONT, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGWINCH, SIGIO, SIGPWR, SIGSYS, SIGINFO, SIGTHR, SIGWAITING, SIGLWP, SIGFREEZE, SIGTHAW, SIGLOST, SIGXRES, SIGJVM1, SIGJVM2, and any real time signals used on the system. Note that not all of these signals are available on all systems.

        If the program was started with SIGHUP or SIGINT ignored, and Notify is called for either signal, a signal handler will be installed for that signal and it will no longer be ignored. If, later, Reset or Ignore is called for that signal, or Stop is called on all channels passed to Notify for that signal, the signal will once again be ignored. Reset will restore the system default behavior for the signal, while Ignore will cause the system to ignore the signal entirely.

        If the program is started with a non-empty signal mask, some signals will be explicitly unblocked as described above. If Notify is called for a blocked signal, it will be unblocked. If, later, Reset is called for that signal, or Stop is called on all channels passed to Notify for that signal, the signal will once again be blocked.

        SIGPIPE

        When a Go program writes to a broken pipe, the kernel will raise a SIGPIPE signal.

        If the program has not called Notify to receive SIGPIPE signals, then the behavior depends on the file descriptor number. A write to a broken pipe on file descriptors 1 or 2 (standard output or standard error) will cause the program to exit with a SIGPIPE signal. A write to a broken pipe on some other file descriptor will take no action on the SIGPIPE signal, and the write will fail with an EPIPE error.

        If the program has called Notify to receive SIGPIPE signals, the file descriptor number does not matter. The SIGPIPE signal will be delivered to the Notify channel, and the write will fail with an EPIPE error.

        This means that, by default, command line programs will behave like typical Unix command line programs, while other programs will not crash with SIGPIPE when writing to a closed network connection.

        Go programs that use cgo or SWIG

        In a Go program that includes non-Go code, typically C/C++ code accessed using cgo or SWIG, Go's startup code normally runs first. It configures the signal handlers as expected by the Go runtime, before the non-Go startup code runs. If the non-Go startup code wishes to install its own signal handlers, it must take certain steps to keep Go working well. This section documents those steps and the overall effect changes to signal handler settings by the non-Go code can have on Go programs. In rare cases, the non-Go code may run before the Go code, in which case the next section also applies.

        If the non-Go code called by the Go program does not change any signal handlers or masks, then the behavior is the same as for a pure Go program.

        If the non-Go code installs any signal handlers, it must use the SA_ONSTACK flag with sigaction. Failing to do so is likely to cause the program to crash if the signal is received. Go programs routinely run with a limited stack, and therefore set up an alternate signal stack.

        If the non-Go code installs a signal handler for any of the synchronous signals (SIGBUS, SIGFPE, SIGSEGV), then it should record the existing Go signal handler. If those signals occur while executing Go code, it should invoke the Go signal handler (whether the signal occurs while executing Go code can be determined by looking at the PC passed to the signal handler). Otherwise some Go run-time panics will not occur as expected.

        If the non-Go code installs a signal handler for any of the asynchronous signals, it may invoke the Go signal handler or not as it chooses. Naturally, if it does not invoke the Go signal handler, the Go behavior described above will not occur. This can be an issue with the SIGPROF signal in particular.

        The non-Go code should not change the signal mask on any threads created by the Go runtime. If the non-Go code starts new threads of its own, it may set the signal mask as it pleases.

        If the non-Go code starts a new thread, changes the signal mask, and then invokes a Go function in that thread, the Go runtime will automatically unblock certain signals: the synchronous signals, SIGILL, SIGTRAP, SIGSTKFLT, SIGCHLD, SIGPROF, SIGCANCEL, and SIGSETXID. When the Go function returns, the non-Go signal mask will be restored.

        If the Go signal handler is invoked on a non-Go thread not running Go code, the handler generally forwards the signal to the non-Go code, as follows. If the signal is SIGPROF, the Go handler does nothing. Otherwise, the Go handler removes itself, unblocks the signal, and raises it again, to invoke any non-Go handler or default system handler. If the program does not exit, the Go handler then reinstalls itself and continues execution of the program.

        If a SIGPIPE signal is received, the Go program will invoke the special handling described above if the SIGPIPE is received on a Go thread. If the SIGPIPE is received on a non-Go thread the signal will be forwarded to the non-Go handler, if any; if there is none the default system handler will cause the program to terminate.

        Non-Go programs that call Go code

        When Go code is built with options like -buildmode=c-shared, it will be run as part of an existing non-Go program. The non-Go code may have already installed signal handlers when the Go code starts (that may also happen in unusual cases when using cgo or SWIG; in that case, the discussion here applies). For -buildmode=c-archive the Go runtime will initialize signals at global constructor time. For -buildmode=c-shared the Go runtime will initialize signals when the shared library is loaded.

        If the Go runtime sees an existing signal handler for the SIGCANCEL or SIGSETXID signals (which are used only on Linux), it will turn on the SA_ONSTACK flag and otherwise keep the signal handler.

        For the synchronous signals and SIGPIPE, the Go runtime will install a signal handler. It will save any existing signal handler. If a synchronous signal arrives while executing non-Go code, the Go runtime will invoke the existing signal handler instead of the Go signal handler.

        Go code built with -buildmode=c-archive or -buildmode=c-shared will not install any other signal handlers by default. If there is an existing signal handler, the Go runtime will turn on the SA_ONSTACK flag and otherwise keep the signal handler. If Notify is called for an asynchronous signal, a Go signal handler will be installed for that signal. If, later, Reset is called for that signal, the original handling for that signal will be reinstalled, restoring the non-Go signal handler if any.

        Go code built without -buildmode=c-archive or -buildmode=c-shared will install a signal handler for the asynchronous signals listed above, and save any existing signal handler. If a signal is delivered to a non-Go thread, it will act as described above, except that if there is an existing non-Go signal handler, that handler will be installed before raising the signal.

        Windows

        On Windows a ^C (Control-C) or ^BREAK (Control-Break) normally cause the program to exit. If Notify is called for os.Interrupt, ^C or ^BREAK will cause os.Interrupt to be sent on the channel, and the program will not exit. If Reset is called, or Stop is called on all channels passed to Notify, then the default behavior will be restored.

        Additionally, if Notify is called, and Windows sends CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT or CTRL_SHUTDOWN_EVENT to the process, Notify will return syscall.SIGTERM. Unlike Control-C and Control-Break, Notify does not change process behavior when either CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT or CTRL_SHUTDOWN_EVENT is received - the process will still get terminated unless it exits. But receiving syscall.SIGTERM will give the process an opportunity to clean up before termination.

        Plan 9

        On Plan 9, signals have type syscall.Note, which is a string. Calling Notify with a syscall.Note will cause that value to be sent on the channel when that string is posted as a note.

        func Ignore

        func Ignore(sig ...os.Signal)

        Ignore causes the provided signals to be ignored. If they are received by the program, nothing will happen. Ignore undoes the effect of any prior calls to Notify for the provided signals. If no signals are provided, all incoming signals will be ignored.

        func Ignored

        func Ignored(sig os.Signal) bool

        Ignored reports whether sig is currently ignored.

        func Notify

        func Notify(c chan<- os.Signal, sig ...os.Signal)

        Notify causes package signal to relay incoming signals to c. If no signals are provided, all incoming signals will be relayed to c. Otherwise, just the provided signals will.

        Package signal will not block sending to c: the caller must ensure that c has sufficient buffer space to keep up with the expected signal rate. For a channel used for notification of just one signal value, a buffer of size 1 is sufficient.

        It is allowed to call Notify multiple times with the same channel: each call expands the set of signals sent to that channel. The only way to remove signals from the set is to call Stop.

        It is allowed to call Notify multiple times with different channels and the same signals: each channel receives copies of incoming signals independently.

        Example

        Code:

        // Set up channel on which to send signal notifications.
        // We must use a buffered channel or risk missing the signal
        // if we're not ready to receive when the signal is sent.
        c := make(chan os.Signal, 1)
        signal.Notify(c, os.Interrupt)
        
        // Block until a signal is received.
        s := <-c
        fmt.Println("Got signal:", s)
        

        Example (AllSignals)

        Code:

        // Set up channel on which to send signal notifications.
        // We must use a buffered channel or risk missing the signal
        // if we're not ready to receive when the signal is sent.
        c := make(chan os.Signal, 1)
        
        // Passing no signals to Notify means that
        // all signals will be sent to the channel.
        signal.Notify(c)
        
        // Block until any signal is received.
        s := <-c
        fmt.Println("Got signal:", s)
        

        func NotifyContext

        func NotifyContext(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc)

        NotifyContext returns a copy of the parent context that is marked done (its Done channel is closed) when one of the listed signals arrives, when the returned stop function is called, or when the parent context's Done channel is closed, whichever happens first.

        The stop function unregisters the signal behavior, which, like signal.Reset, may restore the default behavior for a given signal. For example, the default behavior of a Go program receiving os.Interrupt is to exit. Calling NotifyContext(parent, os.Interrupt) will change the behavior to cancel the returned context. Future interrupts received will not trigger the default (exit) behavior until the returned stop function is called.

        The stop function releases resources associated with it, so code should call stop as soon as the operations running in this Context complete and signals no longer need to be diverted to the context.

        Example

        This example passes a context with a signal to tell a blocking function that it should abandon its work after a signal is received.

        Code:

        package signal_test
        
        import (
            "context"
            "fmt"
            "log"
            "os"
            "os/signal"
        )
        
        var neverReady = make(chan struct{}) // never closed
        
        // This example passes a context with a signal to tell a blocking function that
        // it should abandon its work after a signal is received.
        func ExampleNotifyContext() {
            ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
            defer stop()
        
            p, err := os.FindProcess(os.Getpid())
            if err != nil {
                log.Fatal(err)
            }
        
            // On a Unix-like system, pressing Ctrl+C on a keyboard sends a
            // SIGINT signal to the process of the program in execution.
            //
            // This example simulates that by sending a SIGINT signal to itself.
            if err := p.Signal(os.Interrupt); err != nil {
                log.Fatal(err)
            }
        
            select {
            case <-neverReady:
                fmt.Println("ready")
            case <-ctx.Done():
                fmt.Println(ctx.Err()) // prints "context canceled"
                stop()                 // stop receiving signal notifications as soon as possible.
            }
        
            // Output:
            // context canceled
        }
        

        func Reset

        func Reset(sig ...os.Signal)

        Reset undoes the effect of any prior calls to Notify for the provided signals. If no signals are provided, all signal handlers will be reset.

        func Stop

        func Stop(c chan<- os.Signal)

        Stop causes package signal to stop relaying incoming signals to c. It undoes the effect of all prior calls to Notify using c. When Stop returns, it is guaranteed that c will receive no more signals.

        user - Go Documentation Server
        ...

        Package user

        import "os/user"
        Overview
        Index

        Overview ▾

        Package user allows user account lookups by name or id.

        For most Unix systems, this package has two internal implementations of resolving user and group ids to names, and listing supplementary group IDs. One is written in pure Go and parses /etc/passwd and /etc/group. The other is cgo-based and relies on the standard C library (libc) routines such as getpwuid_r, getgrnam_r, and getgrouplist.

        When cgo is available, and the required routines are implemented in libc for a particular platform, cgo-based (libc-backed) code is used. This can be overridden by using osusergo build tag, which enforces the pure Go implementation.

        type Group

        Group represents a grouping of users.

        On POSIX systems Gid contains a decimal number representing the group ID.

        type Group struct {
            Gid  string // group ID
            Name string // group name
        }
        

        func LookupGroup

        func LookupGroup(name string) (*Group, error)

        LookupGroup looks up a group by name. If the group cannot be found, the returned error is of type UnknownGroupError.

        func LookupGroupId

        func LookupGroupId(gid string) (*Group, error)

        LookupGroupId looks up a group by groupid. If the group cannot be found, the returned error is of type UnknownGroupIdError.

        type UnknownGroupError

        UnknownGroupError is returned by LookupGroup when a group cannot be found.

        type UnknownGroupError string

        func (UnknownGroupError) Error

        func (e UnknownGroupError) Error() string

        type UnknownGroupIdError

        UnknownGroupIdError is returned by LookupGroupId when a group cannot be found.

        type UnknownGroupIdError string

        func (UnknownGroupIdError) Error

        func (e UnknownGroupIdError) Error() string

        type UnknownUserError

        UnknownUserError is returned by Lookup when a user cannot be found.

        type UnknownUserError string

        func (UnknownUserError) Error

        func (e UnknownUserError) Error() string

        type UnknownUserIdError

        UnknownUserIdError is returned by LookupId when a user cannot be found.

        type UnknownUserIdError int

        func (UnknownUserIdError) Error

        func (e UnknownUserIdError) Error() string

        type User

        User represents a user account.

        type User struct {
            // Uid is the user ID.
            // On POSIX systems, this is a decimal number representing the uid.
            // On Windows, this is a security identifier (SID) in a string format.
            // On Plan 9, this is the contents of /dev/user.
            Uid string
            // Gid is the primary group ID.
            // On POSIX systems, this is a decimal number representing the gid.
            // On Windows, this is a SID in a string format.
            // On Plan 9, this is the contents of /dev/user.
            Gid string
            // Username is the login name.
            Username string
            // Name is the user's real or display name.
            // It might be blank.
            // On POSIX systems, this is the first (or only) entry in the GECOS field
            // list.
            // On Windows, this is the user's display name.
            // On Plan 9, this is the contents of /dev/user.
            Name string
            // HomeDir is the path to the user's home directory (if they have one).
            HomeDir string
        }
        

        func Current

        func Current() (*User, error)

        Current returns the current user.

        The first call will cache the current user information. Subsequent calls will return the cached value and will not reflect changes to the current user.

        func Lookup

        func Lookup(username string) (*User, error)

        Lookup looks up a user by username. If the user cannot be found, the returned error is of type UnknownUserError.

        func LookupId

        func LookupId(uid string) (*User, error)

        LookupId looks up a user by userid. If the user cannot be found, the returned error is of type UnknownUserIdError.

        func (*User) GroupIds

        func (u *User) GroupIds() ([]string, error)

        GroupIds returns the list of group IDs that the user is a member of.

        path - Go Documentation Server
        ...

        Package path

        Overview ▾

        Package path implements utility routines for manipulating slash-separated paths.

        The path package should only be used for paths separated by forward slashes, such as the paths in URLs. This package does not deal with Windows paths with drive letters or backslashes; to manipulate operating system paths, use the path/filepath package.

        Variables

        ErrBadPattern indicates a pattern was malformed.

        var ErrBadPattern = errors.New("syntax error in pattern")

        func Base

        func Base(path string) string

        Base returns the last element of path. Trailing slashes are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of slashes, Base returns "/".

        Example

        Code:

        fmt.Println(path.Base("/a/b"))
        fmt.Println(path.Base("/"))
        fmt.Println(path.Base(""))
        

        Output:

        b
        /
        .
        

        func Clean

        func Clean(path string) string

        Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:

        1. Replace multiple slashes with a single slash.
        2. Eliminate each . path name element (the current directory).
        3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
        4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

        The returned path ends in a slash only if it is the root "/".

        If the result of this process is an empty string, Clean returns the string ".".

        See also Rob Pike, “Lexical File Names in Plan 9 or Getting Dot-Dot Right,” https://9p.io/sys/doc/lexnames.html

        Example

        Code:

        paths := []string{
            "a/c",
            "a//c",
            "a/c/.",
            "a/c/b/..",
            "/../a/c",
            "/../a/b/../././/c",
            "",
        }
        
        for _, p := range paths {
            fmt.Printf("Clean(%q) = %q\n", p, path.Clean(p))
        }
        
        

        Output:

        Clean("a/c") = "a/c"
        Clean("a//c") = "a/c"
        Clean("a/c/.") = "a/c"
        Clean("a/c/b/..") = "a/c"
        Clean("/../a/c") = "/a/c"
        Clean("/../a/b/../././/c") = "/a/c"
        Clean("") = "."
        

        func Dir

        func Dir(path string) string

        Dir returns all but the last element of path, typically the path's directory. After dropping the final element using Split, the path is Cleaned and trailing slashes are removed. If the path is empty, Dir returns ".". If the path consists entirely of slashes followed by non-slash bytes, Dir returns a single slash. In any other case, the returned path does not end in a slash.

        Example

        Code:

        fmt.Println(path.Dir("/a/b/c"))
        fmt.Println(path.Dir("a/b/c"))
        fmt.Println(path.Dir("/a/"))
        fmt.Println(path.Dir("a/"))
        fmt.Println(path.Dir("/"))
        fmt.Println(path.Dir(""))
        

        Output:

        /a/b
        a/b
        /a
        a
        /
        .
        

        func Ext

        func Ext(path string) string

        Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final slash-separated element of path; it is empty if there is no dot.

        Example

        Code:

        fmt.Println(path.Ext("/a/b/c/bar.css"))
        fmt.Println(path.Ext("/"))
        fmt.Println(path.Ext(""))
        

        Output:

        .css
        

        func IsAbs

        func IsAbs(path string) bool

        IsAbs reports whether the path is absolute.

        Example

        Code:

        fmt.Println(path.IsAbs("/dev/null"))
        

        Output:

        true
        

        func Join

        func Join(elem ...string) string

        Join joins any number of path elements into a single path, separating them with slashes. Empty elements are ignored. The result is Cleaned. However, if the argument list is empty or all its elements are empty, Join returns an empty string.

        Example

        Code:

        fmt.Println(path.Join("a", "b", "c"))
        fmt.Println(path.Join("a", "b/c"))
        fmt.Println(path.Join("a/b", "c"))
        
        fmt.Println(path.Join("a/b", "../../../xyz"))
        
        fmt.Println(path.Join("", ""))
        fmt.Println(path.Join("a", ""))
        fmt.Println(path.Join("", "a"))
        
        

        Output:

        a/b/c
        a/b/c
        a/b/c
        ../xyz
        
        a
        a
        

        func Match

        func Match(pattern, name string) (matched bool, err error)

        Match reports whether name matches the shell pattern. The pattern syntax is:

        pattern:
        	{ term }
        term:
        	'*'         matches any sequence of non-/ characters
        	'?'         matches any single non-/ character
        	'[' [ '^' ] { character-range } ']'
        	            character class (must be non-empty)
        	c           matches character c (c != '*', '?', '\\', '[')
        	'\\' c      matches character c
        
        character-range:
        	c           matches character c (c != '\\', '-', ']')
        	'\\' c      matches character c
        	lo '-' hi   matches character c for lo <= c <= hi
        

        Match requires pattern to match all of name, not just a substring. The only possible returned error is ErrBadPattern, when pattern is malformed.

        Example

        Code:

        fmt.Println(path.Match("abc", "abc"))
        fmt.Println(path.Match("a*", "abc"))
        fmt.Println(path.Match("a*/b", "a/c/b"))
        

        Output:

        true <nil>
        true <nil>
        false <nil>
        

        func Split

        func Split(path string) (dir, file string)

        Split splits path immediately following the final slash, separating it into a directory and file name component. If there is no slash in path, Split returns an empty dir and file set to path. The returned values have the property that path = dir+file.

        Example

        Code:

        split := func(s string) {
            dir, file := path.Split(s)
            fmt.Printf("path.Split(%q) = dir: %q, file: %q\n", s, dir, file)
        }
        split("static/myfile.css")
        split("myfile.css")
        split("")
        

        Output:

        path.Split("static/myfile.css") = dir: "static/", file: "myfile.css"
        path.Split("myfile.css") = dir: "", file: "myfile.css"
        path.Split("") = dir: "", file: ""
        

        Subdirectories

        Name Synopsis
        ..
        filepath Package filepath implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file paths.
        filepath - Go Documentation Server
        ...

        Package filepath

        import "path/filepath"
        Overview
        Index
        Examples

        Overview ▾

        Package filepath implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file paths.

        The filepath package uses either forward slashes or backslashes, depending on the operating system. To process paths such as URLs that always use forward slashes regardless of the operating system, see the path package.

        Constants

        const (
            Separator     = os.PathSeparator
            ListSeparator = os.PathListSeparator
        )

        Variables

        ErrBadPattern indicates a pattern was malformed.

        var ErrBadPattern = errors.New("syntax error in pattern")

        SkipAll is used as a return value from WalkFunc to indicate that all remaining files and directories are to be skipped. It is not returned as an error by any function.

        var SkipAll error = fs.SkipAll

        SkipDir is used as a return value from WalkFunc to indicate that the directory named in the call is to be skipped. It is not returned as an error by any function.

        var SkipDir error = fs.SkipDir

        func Abs

        func Abs(path string) (string, error)

        Abs returns an absolute representation of path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path. The absolute path name for a given file is not guaranteed to be unique. Abs calls Clean on the result.

        func Base

        func Base(path string) string

        Base returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of separators, Base returns a single separator.

        Example

        Code:

        fmt.Println("On Unix:")
        fmt.Println(filepath.Base("/foo/bar/baz.js"))
        fmt.Println(filepath.Base("/foo/bar/baz"))
        fmt.Println(filepath.Base("/foo/bar/baz/"))
        fmt.Println(filepath.Base("dev.txt"))
        fmt.Println(filepath.Base("../todo.txt"))
        fmt.Println(filepath.Base(".."))
        fmt.Println(filepath.Base("."))
        fmt.Println(filepath.Base("/"))
        fmt.Println(filepath.Base(""))
        
        

        Output:

        On Unix:
        baz.js
        baz
        baz
        dev.txt
        todo.txt
        ..
        .
        /
        .
        

        func Clean

        func Clean(path string) string

        Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:

        1. Replace multiple Separator elements with a single one.
        2. Eliminate each . path name element (the current directory).
        3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
        4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path, assuming Separator is '/'.

        The returned path ends in a slash only if it represents a root directory, such as "/" on Unix or `C:\` on Windows.

        Finally, any occurrences of slash are replaced by Separator.

        If the result of this process is an empty string, Clean returns the string ".".

        On Windows, Clean does not modify the volume name other than to replace occurrences of "/" with `\`. For example, Clean("//host/share/../x") returns `\\host\share\x`.

        See also Rob Pike, “Lexical File Names in Plan 9 or Getting Dot-Dot Right,” https://9p.io/sys/doc/lexnames.html

        func Dir

        func Dir(path string) string

        Dir returns all but the last element of path, typically the path's directory. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed. If the path is empty, Dir returns ".". If the path consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory.

        Example

        Code:

        fmt.Println("On Unix:")
        fmt.Println(filepath.Dir("/foo/bar/baz.js"))
        fmt.Println(filepath.Dir("/foo/bar/baz"))
        fmt.Println(filepath.Dir("/foo/bar/baz/"))
        fmt.Println(filepath.Dir("/dirty//path///"))
        fmt.Println(filepath.Dir("dev.txt"))
        fmt.Println(filepath.Dir("../todo.txt"))
        fmt.Println(filepath.Dir(".."))
        fmt.Println(filepath.Dir("."))
        fmt.Println(filepath.Dir("/"))
        fmt.Println(filepath.Dir(""))
        
        

        Output:

        On Unix:
        /foo/bar
        /foo/bar
        /foo/bar/baz
        /dirty/path
        .
        ..
        .
        .
        /
        .
        
        func EvalSymlinks(path string) (string, error)

        EvalSymlinks returns the path name after the evaluation of any symbolic links. If path is relative the result will be relative to the current directory, unless one of the components is an absolute symbolic link. EvalSymlinks calls Clean on the result.

        func Ext

        func Ext(path string) string

        Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final element of path; it is empty if there is no dot.

        Example

        Code:

        fmt.Printf("No dots: %q\n", filepath.Ext("index"))
        fmt.Printf("One dot: %q\n", filepath.Ext("index.js"))
        fmt.Printf("Two dots: %q\n", filepath.Ext("main.test.js"))
        

        Output:

        No dots: ""
        One dot: ".js"
        Two dots: ".js"
        

        func FromSlash

        func FromSlash(path string) string

        FromSlash returns the result of replacing each slash ('/') character in path with a separator character. Multiple slashes are replaced by multiple separators.

        func Glob

        func Glob(pattern string) (matches []string, err error)

        Glob returns the names of all files matching pattern or nil if there is no matching file. The syntax of patterns is the same as in Match. The pattern may describe hierarchical names such as /usr/*/bin/ed (assuming the Separator is '/').

        Glob ignores file system errors such as I/O errors reading directories. The only possible returned error is ErrBadPattern, when pattern is malformed.

        func HasPrefix

        func HasPrefix(p, prefix string) bool

        HasPrefix exists for historical compatibility and should not be used.

        Deprecated: HasPrefix does not respect path boundaries and does not ignore case when required.

        func IsAbs

        func IsAbs(path string) bool

        IsAbs reports whether the path is absolute.

        Example

        Code:

        fmt.Println("On Unix:")
        fmt.Println(filepath.IsAbs("/home/gopher"))
        fmt.Println(filepath.IsAbs(".bashrc"))
        fmt.Println(filepath.IsAbs(".."))
        fmt.Println(filepath.IsAbs("."))
        fmt.Println(filepath.IsAbs("/"))
        fmt.Println(filepath.IsAbs(""))
        
        

        Output:

        On Unix:
        true
        false
        false
        false
        true
        false
        

        func IsLocal

        func IsLocal(path string) bool

        IsLocal reports whether path, using lexical analysis only, has all of these properties:

        • is within the subtree rooted at the directory in which path is evaluated
        • is not an absolute path
        • is not empty
        • on Windows, is not a reserved name such as "NUL"

        If IsLocal(path) returns true, then Join(base, path) will always produce a path contained within base and Clean(path) will always produce an unrooted path with no ".." path elements.

        IsLocal is a purely lexical operation. In particular, it does not account for the effect of any symbolic links that may exist in the filesystem.

        func Join

        func Join(elem ...string) string

        Join joins any number of path elements into a single path, separating them with an OS specific Separator. Empty elements are ignored. The result is Cleaned. However, if the argument list is empty or all its elements are empty, Join returns an empty string. On Windows, the result will only be a UNC path if the first non-empty element is a UNC path.

        Example

        Code:

        fmt.Println("On Unix:")
        fmt.Println(filepath.Join("a", "b", "c"))
        fmt.Println(filepath.Join("a", "b/c"))
        fmt.Println(filepath.Join("a/b", "c"))
        fmt.Println(filepath.Join("a/b", "/c"))
        
        fmt.Println(filepath.Join("a/b", "../../../xyz"))
        
        

        Output:

        On Unix:
        a/b/c
        a/b/c
        a/b/c
        a/b/c
        ../xyz
        

        func Match

        func Match(pattern, name string) (matched bool, err error)

        Match reports whether name matches the shell file name pattern. The pattern syntax is:

        pattern:
        	{ term }
        term:
        	'*'         matches any sequence of non-Separator characters
        	'?'         matches any single non-Separator character
        	'[' [ '^' ] { character-range } ']'
        	            character class (must be non-empty)
        	c           matches character c (c != '*', '?', '\\', '[')
        	'\\' c      matches character c
        
        character-range:
        	c           matches character c (c != '\\', '-', ']')
        	'\\' c      matches character c
        	lo '-' hi   matches character c for lo <= c <= hi
        

        Match requires pattern to match all of name, not just a substring. The only possible returned error is ErrBadPattern, when pattern is malformed.

        On Windows, escaping is disabled. Instead, '\\' is treated as path separator.

        Example

        Code:

        fmt.Println("On Unix:")
        fmt.Println(filepath.Match("/home/catch/*", "/home/catch/foo"))
        fmt.Println(filepath.Match("/home/catch/*", "/home/catch/foo/bar"))
        fmt.Println(filepath.Match("/home/?opher", "/home/gopher"))
        fmt.Println(filepath.Match("/home/\\*", "/home/*"))
        
        

        Output:

        On Unix:
        true <nil>
        false <nil>
        true <nil>
        true <nil>
        

        func Rel

        func Rel(basepath, targpath string) (string, error)

        Rel returns a relative path that is lexically equivalent to targpath when joined to basepath with an intervening separator. That is, Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself. On success, the returned path will always be relative to basepath, even if basepath and targpath share no elements. An error is returned if targpath can't be made relative to basepath or if knowing the current working directory would be necessary to compute it. Rel calls Clean on the result.

        Example

        Code:

        paths := []string{
            "/a/b/c",
            "/b/c",
            "./b/c",
        }
        base := "/a"
        
        fmt.Println("On Unix:")
        for _, p := range paths {
            rel, err := filepath.Rel(base, p)
            fmt.Printf("%q: %q %v\n", p, rel, err)
        }
        
        

        Output:

        On Unix:
        "/a/b/c": "b/c" <nil>
        "/b/c": "../b/c" <nil>
        "./b/c": "" Rel: can't make ./b/c relative to /a
        

        func Split

        func Split(path string) (dir, file string)

        Split splits path immediately following the final Separator, separating it into a directory and file name component. If there is no Separator in path, Split returns an empty dir and file set to path. The returned values have the property that path = dir+file.

        Example

        Code:

        paths := []string{
            "/home/arnie/amelia.jpg",
            "/mnt/photos/",
            "rabbit.jpg",
            "/usr/local//go",
        }
        fmt.Println("On Unix:")
        for _, p := range paths {
            dir, file := filepath.Split(p)
            fmt.Printf("input: %q\n\tdir: %q\n\tfile: %q\n", p, dir, file)
        }
        

        Output:

        On Unix:
        input: "/home/arnie/amelia.jpg"
        	dir: "/home/arnie/"
        	file: "amelia.jpg"
        input: "/mnt/photos/"
        	dir: "/mnt/photos/"
        	file: ""
        input: "rabbit.jpg"
        	dir: ""
        	file: "rabbit.jpg"
        input: "/usr/local//go"
        	dir: "/usr/local//"
        	file: "go"
        

        func SplitList

        func SplitList(path string) []string

        SplitList splits a list of paths joined by the OS-specific ListSeparator, usually found in PATH or GOPATH environment variables. Unlike strings.Split, SplitList returns an empty slice when passed an empty string.

        Example

        Code:

        fmt.Println("On Unix:", filepath.SplitList("/a/b/c:/usr/bin"))
        

        Output:

        On Unix: [/a/b/c /usr/bin]
        

        func ToSlash

        func ToSlash(path string) string

        ToSlash returns the result of replacing each separator character in path with a slash ('/') character. Multiple separators are replaced by multiple slashes.

        func VolumeName

        func VolumeName(path string) string

        VolumeName returns leading volume name. Given "C:\foo\bar" it returns "C:" on Windows. Given "\\host\share\foo" it returns "\\host\share". On other platforms it returns "".

        func Walk

        func Walk(root string, fn WalkFunc) error

        Walk walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.

        All errors that arise visiting files and directories are filtered by fn: see the WalkFunc documentation for details.

        The files are walked in lexical order, which makes the output deterministic but requires Walk to read an entire directory into memory before proceeding to walk that directory.

        Walk does not follow symbolic links.

        Walk is less efficient than WalkDir, introduced in Go 1.16, which avoids calling os.Lstat on every visited file or directory.

        Example

        Code:

        package filepath_test
        
        import (
            "fmt"
            "io/fs"
            "os"
            "path/filepath"
        )
        
        func prepareTestDirTree(tree string) (string, error) {
            tmpDir, err := os.MkdirTemp("", "")
            if err != nil {
                return "", fmt.Errorf("error creating temp directory: %v\n", err)
            }
        
            err = os.MkdirAll(filepath.Join(tmpDir, tree), 0755)
            if err != nil {
                os.RemoveAll(tmpDir)
                return "", err
            }
        
            return tmpDir, nil
        }
        
        func ExampleWalk() {
            tmpDir, err := prepareTestDirTree("dir/to/walk/skip")
            if err != nil {
                fmt.Printf("unable to create test dir tree: %v\n", err)
                return
            }
            defer os.RemoveAll(tmpDir)
            os.Chdir(tmpDir)
        
            subDirToSkip := "skip"
        
            fmt.Println("On Unix:")
            err = filepath.Walk(".", func(path string, info fs.FileInfo, err error) error {
                if err != nil {
                    fmt.Printf("prevent panic by handling failure accessing a path %q: %v\n", path, err)
                    return err
                }
                if info.IsDir() && info.Name() == subDirToSkip {
                    fmt.Printf("skipping a dir without errors: %+v \n", info.Name())
                    return filepath.SkipDir
                }
                fmt.Printf("visited file or dir: %q\n", path)
                return nil
            })
            if err != nil {
                fmt.Printf("error walking the path %q: %v\n", tmpDir, err)
                return
            }
            // Output:
            // On Unix:
            // visited file or dir: "."
            // visited file or dir: "dir"
            // visited file or dir: "dir/to"
            // visited file or dir: "dir/to/walk"
            // skipping a dir without errors: skip
        }
        

        func WalkDir

        func WalkDir(root string, fn fs.WalkDirFunc) error

        WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.

        All errors that arise visiting files and directories are filtered by fn: see the fs.WalkDirFunc documentation for details.

        The files are walked in lexical order, which makes the output deterministic but requires WalkDir to read an entire directory into memory before proceeding to walk that directory.

        WalkDir does not follow symbolic links.

        WalkDir calls fn with paths that use the separator character appropriate for the operating system. This is unlike io/fs.WalkDir, which always uses slash separated paths.

        type WalkFunc

        WalkFunc is the type of the function called by Walk to visit each file or directory.

        The path argument contains the argument to Walk as a prefix. That is, if Walk is called with root argument "dir" and finds a file named "a" in that directory, the walk function will be called with argument "dir/a".

        The directory and file are joined with Join, which may clean the directory name: if Walk is called with the root argument "x/../dir" and finds a file named "a" in that directory, the walk function will be called with argument "dir/a", not "x/../dir/a".

        The info argument is the fs.FileInfo for the named path.

        The error result returned by the function controls how Walk continues. If the function returns the special value SkipDir, Walk skips the current directory (path if info.IsDir() is true, otherwise path's parent directory). If the function returns the special value SkipAll, Walk skips all remaining files and directories. Otherwise, if the function returns a non-nil error, Walk stops entirely and returns that error.

        The err argument reports an error related to path, signaling that Walk will not walk into that directory. The function can decide how to handle that error; as described earlier, returning the error will cause Walk to stop walking the entire tree.

        Walk calls the function with a non-nil err argument in two cases.

        First, if an os.Lstat on the root directory or any directory or file in the tree fails, Walk calls the function with path set to that directory or file's path, info set to nil, and err set to the error from os.Lstat.

        Second, if a directory's Readdirnames method fails, Walk calls the function with path set to the directory's path, info, set to an fs.FileInfo describing the directory, and err set to the error from Readdirnames.

        type WalkFunc func(path string, info fs.FileInfo, err error) error
        plugin - Go Documentation Server
        ...

        Package plugin

        import "plugin"
        Overview
        Index

        Overview ▾

        Package plugin implements loading and symbol resolution of Go plugins.

        A plugin is a Go main package with exported functions and variables that has been built with:

        go build -buildmode=plugin
        

        When a plugin is first opened, the init functions of all packages not already part of the program are called. The main function is not run. A plugin is only initialized once, and cannot be closed.

        Warnings

        The ability to dynamically load parts of an application during execution, perhaps based on user-defined configuration, may be a useful building block in some designs. In particular, because applications and dynamically loaded functions can share data structures directly, plugins may enable very high-performance integration of separate parts.

        However, the plugin mechanism has many significant drawbacks that should be considered carefully during the design. For example:

        • Plugins are currently supported only on Linux, FreeBSD, and macOS, making them unsuitable for applications intended to be portable.

        • Applications that use plugins may require careful configuration to ensure that the various parts of the program be made available in the correct location in the file system (or container image). By contrast, deploying an application consisting of a single static executable is straightforward.

        • Reasoning about program initialization is more difficult when some packages may not be initialized until long after the application has started running.

        • Bugs in applications that load plugins could be exploited by an attacker to load dangerous or untrusted libraries.

        • Runtime crashes are likely to occur unless all parts of the program (the application and all its plugins) are compiled using exactly the same version of the toolchain, the same build tags, and the same values of certain flags and environment variables.

        • Similar crashing problems are likely to arise unless all common dependencies of the application and its plugins are built from exactly the same source code.

        • Together, these restrictions mean that, in practice, the application and its plugins must all be built together by a single person or component of a system. In that case, it may be simpler for that person or component to generate Go source files that blank-import the desired set of plugins and then compile a static executable in the usual way.

        For these reasons, many users decide that traditional interprocess communication (IPC) mechanisms such as sockets, pipes, remote procedure call (RPC), shared memory mappings, or file system operations may be more suitable despite the performance overheads.

        type Plugin

        Plugin is a loaded Go plugin.

        type Plugin struct {
            // contains filtered or unexported fields
        }
        

        func Open

        func Open(path string) (*Plugin, error)

        Open opens a Go plugin. If a path has already been opened, then the existing *Plugin is returned. It is safe for concurrent use by multiple goroutines.

        func (*Plugin) Lookup

        func (p *Plugin) Lookup(symName string) (Symbol, error)

        Lookup searches for a symbol named symName in plugin p. A symbol is any exported variable or function. It reports an error if the symbol is not found. It is safe for concurrent use by multiple goroutines.

        type Symbol

        A Symbol is a pointer to a variable or function.

        For example, a plugin defined as

        package main
        
        import "fmt"
        
        var V int
        
        func F() { fmt.Printf("Hello, number %d\n", V) }
        

        may be loaded with the Open function and then the exported package symbols V and F can be accessed

        p, err := plugin.Open("plugin_name.so")
        if err != nil {
        	panic(err)
        }
        v, err := p.Lookup("V")
        if err != nil {
        	panic(err)
        }
        f, err := p.Lookup("F")
        if err != nil {
        	panic(err)
        }
        *v.(*int) = 7
        f.(func())() // prints "Hello, number 7"
        
        type Symbol any
        reflect - Go Documentation Server
        ...

        Package reflect

        Overview ▾

        Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types. The typical use is to take a value with static type interface{} and extract its dynamic type information by calling TypeOf, which returns a Type.

        A call to ValueOf returns a Value representing the run-time data. Zero takes a Type and returns a Value representing a zero value for that type.

        See "The Laws of Reflection" for an introduction to reflection in Go: https://golang.org/doc/articles/laws_of_reflection.html

        Index ▾

        Constants
        func Copy(dst, src Value) int
        func DeepEqual(x, y any) bool
        func Swapper(slice any) func(i, j int)
        type ChanDir
            func (d ChanDir) String() string
        type Kind
            func (k Kind) String() string
        type MapIter
            func (iter *MapIter) Key() Value
            func (iter *MapIter) Next() bool
            func (iter *MapIter) Reset(v Value)
            func (iter *MapIter) Value() Value
        type Method
            func (m Method) IsExported() bool
        type SelectCase
        type SelectDir
        type SliceHeader
        type StringHeader
        type StructField
            func VisibleFields(t Type) []StructField
            func (f StructField) IsExported() bool
        type StructTag
            func (tag StructTag) Get(key string) string
            func (tag StructTag) Lookup(key string) (value string, ok bool)
        type Type
            func ArrayOf(length int, elem Type) Type
            func ChanOf(dir ChanDir, t Type) Type
            func FuncOf(in, out []Type, variadic bool) Type
            func MapOf(key, elem Type) Type
            func PointerTo(t Type) Type
            func PtrTo(t Type) Type
            func SliceOf(t Type) Type
            func StructOf(fields []StructField) Type
            func TypeFor[T any]() Type
            func TypeOf(i any) Type
        type Value
            func Append(s Value, x ...Value) Value
            func AppendSlice(s, t Value) Value
            func Indirect(v Value) Value
            func MakeChan(typ Type, buffer int) Value
            func MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value
            func MakeMap(typ Type) Value
            func MakeMapWithSize(typ Type, n int) Value
            func MakeSlice(typ Type, len, cap int) Value
            func New(typ Type) Value
            func NewAt(typ Type, p unsafe.Pointer) Value
            func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool)
            func ValueOf(i any) Value
            func Zero(typ Type) Value
            func (v Value) Addr() Value
            func (v Value) Bool() bool
            func (v Value) Bytes() []byte
            func (v Value) Call(in []Value) []Value
            func (v Value) CallSlice(in []Value) []Value
            func (v Value) CanAddr() bool
            func (v Value) CanComplex() bool
            func (v Value) CanConvert(t Type) bool
            func (v Value) CanFloat() bool
            func (v Value) CanInt() bool
            func (v Value) CanInterface() bool
            func (v Value) CanSet() bool
            func (v Value) CanUint() bool
            func (v Value) Cap() int
            func (v Value) Clear()
            func (v Value) Close()
            func (v Value) Comparable() bool
            func (v Value) Complex() complex128
            func (v Value) Convert(t Type) Value
            func (v Value) Elem() Value
            func (v Value) Equal(u Value) bool
            func (v Value) Field(i int) Value
            func (v Value) FieldByIndex(index []int) Value
            func (v Value) FieldByIndexErr(index []int) (Value, error)
            func (v Value) FieldByName(name string) Value
            func (v Value) FieldByNameFunc(match func(string) bool) Value
            func (v Value) Float() float64
            func (v Value) Grow(n int)
            func (v Value) Index(i int) Value
            func (v Value) Int() int64
            func (v Value) Interface() (i any)
            func (v Value) InterfaceData() [2]uintptr
            func (v Value) IsNil() bool
            func (v Value) IsValid() bool
            func (v Value) IsZero() bool
            func (v Value) Kind() Kind
            func (v Value) Len() int
            func (v Value) MapIndex(key Value) Value
            func (v Value) MapKeys() []Value
            func (v Value) MapRange() *MapIter
            func (v Value) Method(i int) Value
            func (v Value) MethodByName(name string) Value
            func (v Value) NumField() int
            func (v Value) NumMethod() int
            func (v Value) OverflowComplex(x complex128) bool
            func (v Value) OverflowFloat(x float64) bool
            func (v Value) OverflowInt(x int64) bool
            func (v Value) OverflowUint(x uint64) bool
            func (v Value) Pointer() uintptr
            func (v Value) Recv() (x Value, ok bool)
            func (v Value) Send(x Value)
            func (v Value) Set(x Value)
            func (v Value) SetBool(x bool)
            func (v Value) SetBytes(x []byte)
            func (v Value) SetCap(n int)
            func (v Value) SetComplex(x complex128)
            func (v Value) SetFloat(x float64)
            func (v Value) SetInt(x int64)
            func (v Value) SetIterKey(iter *MapIter)
            func (v Value) SetIterValue(iter *MapIter)
            func (v Value) SetLen(n int)
            func (v Value) SetMapIndex(key, elem Value)
            func (v Value) SetPointer(x unsafe.Pointer)
            func (v Value) SetString(x string)
            func (v Value) SetUint(x uint64)
            func (v Value) SetZero()
            func (v Value) Slice(i, j int) Value
            func (v Value) Slice3(i, j, k int) Value
            func (v Value) String() string
            func (v Value) TryRecv() (x Value, ok bool)
            func (v Value) TrySend(x Value) bool
            func (v Value) Type() Type
            func (v Value) Uint() uint64
            func (v Value) UnsafeAddr() uintptr
            func (v Value) UnsafePointer() unsafe.Pointer
        type ValueError
            func (e *ValueError) Error() string
        Bugs

        Package files

        abi.go deepequal.go float32reg_generic.go makefunc.go swapper.go type.go value.go visiblefields.go

        Constants

        Ptr is the old name for the Pointer kind.

        const Ptr = Pointer

        func Copy

        func Copy(dst, src Value) int

        Copy copies the contents of src into dst until either dst has been filled or src has been exhausted. It returns the number of elements copied. Dst and src each must have kind Slice or Array, and dst and src must have the same element type.

        As a special case, src can have kind String if the element type of dst is kind Uint8.

        func DeepEqual

        func DeepEqual(x, y any) bool

        DeepEqual reports whether x and y are “deeply equal,” defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal.

        Array values are deeply equal when their corresponding elements are deeply equal.

        Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.

        Func values are deeply equal if both are nil; otherwise they are not deeply equal.

        Interface values are deeply equal if they hold deeply equal concrete values.

        Map values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they are the same map object or their corresponding keys (matched using Go equality) map to deeply equal values.

        Pointer values are deeply equal if they are equal using Go's == operator or if they point to deeply equal values.

        Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.

        Other values - numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.

        In general DeepEqual is a recursive relaxation of Go's == operator. However, this idea is impossible to implement without some inconsistency. Specifically, it is possible for a value to be unequal to itself, either because it is of func type (uncomparable in general) or because it is a floating-point NaN value (not equal to itself in floating-point comparison), or because it is an array, struct, or interface containing such a value. On the other hand, pointer values are always equal to themselves, even if they point at or contain such problematic values, because they compare equal using Go's == operator, and that is a sufficient condition to be deeply equal, regardless of content. DeepEqual has been defined so that the same short-cut applies to slices and maps: if x and y are the same slice or the same map, they are deeply equal regardless of content.

        As DeepEqual traverses the data values it may find a cycle. The second and subsequent times that DeepEqual compares two pointer values that have been compared before, it treats the values as equal rather than examining the values to which they point. This ensures that DeepEqual terminates.

        func Swapper

        func Swapper(slice any) func(i, j int)

        Swapper returns a function that swaps the elements in the provided slice.

        Swapper panics if the provided interface is not a slice.

        type ChanDir

        ChanDir represents a channel type's direction.

        type ChanDir int
        const (
            RecvDir ChanDir             = 1 << iota // <-chan
            SendDir                                 // chan<-
            BothDir = RecvDir | SendDir             // chan
        )

        func (ChanDir) String

        func (d ChanDir) String() string

        type Kind

        A Kind represents the specific kind of type that a Type represents. The zero Kind is not a valid kind.

        type Kind uint
        const (
            Invalid Kind = iota
            Bool
            Int
            Int8
            Int16
            Int32
            Int64
            Uint
            Uint8
            Uint16
            Uint32
            Uint64
            Uintptr
            Float32
            Float64
            Complex64
            Complex128
            Array
            Chan
            Func
            Interface
            Map
            Pointer
            Slice
            String
            Struct
            UnsafePointer
        )

        Example

        Code:

        for _, v := range []any{"hi", 42, func() {}} {
            switch v := reflect.ValueOf(v); v.Kind() {
            case reflect.String:
                fmt.Println(v.String())
            case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
                fmt.Println(v.Int())
            default:
                fmt.Printf("unhandled kind %s", v.Kind())
            }
        }
        
        

        Output:

        hi
        42
        unhandled kind func
        

        func (Kind) String

        func (k Kind) String() string

        String returns the name of k.

        type MapIter

        A MapIter is an iterator for ranging over a map. See Value.MapRange.

        type MapIter struct {
            // contains filtered or unexported fields
        }
        

        func (*MapIter) Key

        func (iter *MapIter) Key() Value

        Key returns the key of iter's current map entry.

        func (*MapIter) Next

        func (iter *MapIter) Next() bool

        Next advances the map iterator and reports whether there is another entry. It returns false when iter is exhausted; subsequent calls to MapIter.Key, MapIter.Value, or MapIter.Next will panic.

        func (*MapIter) Reset

        func (iter *MapIter) Reset(v Value)

        Reset modifies iter to iterate over v. It panics if v's Kind is not Map and v is not the zero Value. Reset(Value{}) causes iter to not to refer to any map, which may allow the previously iterated-over map to be garbage collected.

        func (*MapIter) Value

        func (iter *MapIter) Value() Value

        Value returns the value of iter's current map entry.

        type Method

        Method represents a single method.

        type Method struct {
            // Name is the method name.
            Name string
        
            // PkgPath is the package path that qualifies a lower case (unexported)
            // method name. It is empty for upper case (exported) method names.
            // The combination of PkgPath and Name uniquely identifies a method
            // in a method set.
            // See https://golang.org/ref/spec#Uniqueness_of_identifiers
            PkgPath string
        
            Type  Type  // method type
            Func  Value // func with receiver as first argument
            Index int   // index for Type.Method
        }
        

        func (Method) IsExported

        func (m Method) IsExported() bool

        IsExported reports whether the method is exported.

        type SelectCase

        A SelectCase describes a single case in a select operation. The kind of case depends on Dir, the communication direction.

        If Dir is SelectDefault, the case represents a default case. Chan and Send must be zero Values.

        If Dir is SelectSend, the case represents a send operation. Normally Chan's underlying value must be a channel, and Send's underlying value must be assignable to the channel's element type. As a special case, if Chan is a zero Value, then the case is ignored, and the field Send will also be ignored and may be either zero or non-zero.

        If Dir is SelectRecv, the case represents a receive operation. Normally Chan's underlying value must be a channel and Send must be a zero Value. If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value. When a receive operation is selected, the received Value is returned by Select.

        type SelectCase struct {
            Dir  SelectDir // direction of case
            Chan Value     // channel to use (for send or receive)
            Send Value     // value to send (for send)
        }
        

        type SelectDir

        A SelectDir describes the communication direction of a select case.

        type SelectDir int
        const (
            SelectSend    SelectDir // case Chan <- Send
            SelectRecv              // case <-Chan:
            SelectDefault           // default
        )

        type SliceHeader

        SliceHeader is the runtime representation of a slice. It cannot be used safely or portably and its representation may change in a later release. Moreover, the Data field is not sufficient to guarantee the data it references will not be garbage collected, so programs must keep a separate, correctly typed pointer to the underlying data.

        Deprecated: Use unsafe.Slice or unsafe.SliceData instead.

        type SliceHeader struct {
            Data uintptr
            Len  int
            Cap  int
        }
        

        type StringHeader

        StringHeader is the runtime representation of a string. It cannot be used safely or portably and its representation may change in a later release. Moreover, the Data field is not sufficient to guarantee the data it references will not be garbage collected, so programs must keep a separate, correctly typed pointer to the underlying data.

        Deprecated: Use unsafe.String or unsafe.StringData instead.

        type StringHeader struct {
            Data uintptr
            Len  int
        }
        

        type StructField

        A StructField describes a single field in a struct.

        type StructField struct {
            // Name is the field name.
            Name string
        
            // PkgPath is the package path that qualifies a lower case (unexported)
            // field name. It is empty for upper case (exported) field names.
            // See https://golang.org/ref/spec#Uniqueness_of_identifiers
            PkgPath string
        
            Type      Type      // field type
            Tag       StructTag // field tag string
            Offset    uintptr   // offset within struct, in bytes
            Index     []int     // index sequence for Type.FieldByIndex
            Anonymous bool      // is an embedded field
        }
        

        func VisibleFields

        func VisibleFields(t Type) []StructField

        VisibleFields returns all the visible fields in t, which must be a struct type. A field is defined as visible if it's accessible directly with a FieldByName call. The returned fields include fields inside anonymous struct members and unexported fields. They follow the same order found in the struct, with anonymous fields followed immediately by their promoted fields.

        For each element e of the returned slice, the corresponding field can be retrieved from a value v of type t by calling v.FieldByIndex(e.Index).

        func (StructField) IsExported

        func (f StructField) IsExported() bool

        IsExported reports whether the field is exported.

        type StructTag

        A StructTag is the tag string in a struct field.

        By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

        type StructTag string

        Example

        Code:

        type S struct {
            F string `species:"gopher" color:"blue"`
        }
        
        s := S{}
        st := reflect.TypeOf(s)
        field := st.Field(0)
        fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
        
        

        Output:

        blue gopher
        

        func (StructTag) Get

        func (tag StructTag) Get(key string) string

        Get returns the value associated with key in the tag string. If there is no such key in the tag, Get returns the empty string. If the tag does not have the conventional format, the value returned by Get is unspecified. To determine whether a tag is explicitly set to the empty string, use Lookup.

        func (StructTag) Lookup

        func (tag StructTag) Lookup(key string) (value string, ok bool)

        Lookup returns the value associated with key in the tag string. If the key is present in the tag the value (which may be empty) is returned. Otherwise the returned value will be the empty string. The ok return value reports whether the value was explicitly set in the tag string. If the tag does not have the conventional format, the value returned by Lookup is unspecified.

        Example

        Code:

        type S struct {
            F0 string `alias:"field_0"`
            F1 string `alias:""`
            F2 string
        }
        
        s := S{}
        st := reflect.TypeOf(s)
        for i := 0; i < st.NumField(); i++ {
            field := st.Field(i)
            if alias, ok := field.Tag.Lookup("alias"); ok {
                if alias == "" {
                    fmt.Println("(blank)")
                } else {
                    fmt.Println(alias)
                }
            } else {
                fmt.Println("(not specified)")
            }
        }
        
        

        Output:

        field_0
        (blank)
        (not specified)
        

        type Type

        Type is the representation of a Go type.

        Not all methods apply to all kinds of types. Restrictions, if any, are noted in the documentation for each method. Use the Kind method to find out the kind of type before calling kind-specific methods. Calling a method inappropriate to the kind of type causes a run-time panic.

        Type values are comparable, such as with the == operator, so they can be used as map keys. Two Type values are equal if they represent identical types.

        type Type interface {
        
            // Align returns the alignment in bytes of a value of
            // this type when allocated in memory.
            Align() int
        
            // FieldAlign returns the alignment in bytes of a value of
            // this type when used as a field in a struct.
            FieldAlign() int
        
            // Method returns the i'th method in the type's method set.
            // It panics if i is not in the range [0, NumMethod()).
            //
            // For a non-interface type T or *T, the returned Method's Type and Func
            // fields describe a function whose first argument is the receiver,
            // and only exported methods are accessible.
            //
            // For an interface type, the returned Method's Type field gives the
            // method signature, without a receiver, and the Func field is nil.
            //
            // Methods are sorted in lexicographic order.
            Method(int) Method
        
            // MethodByName returns the method with that name in the type's
            // method set and a boolean indicating if the method was found.
            //
            // For a non-interface type T or *T, the returned Method's Type and Func
            // fields describe a function whose first argument is the receiver.
            //
            // For an interface type, the returned Method's Type field gives the
            // method signature, without a receiver, and the Func field is nil.
            MethodByName(string) (Method, bool)
        
            // NumMethod returns the number of methods accessible using Method.
            //
            // For a non-interface type, it returns the number of exported methods.
            //
            // For an interface type, it returns the number of exported and unexported methods.
            NumMethod() int
        
            // Name returns the type's name within its package for a defined type.
            // For other (non-defined) types it returns the empty string.
            Name() string
        
            // PkgPath returns a defined type's package path, that is, the import path
            // that uniquely identifies the package, such as "encoding/base64".
            // If the type was predeclared (string, error) or not defined (*T, struct{},
            // []int, or A where A is an alias for a non-defined type), the package path
            // will be the empty string.
            PkgPath() string
        
            // Size returns the number of bytes needed to store
            // a value of the given type; it is analogous to unsafe.Sizeof.
            Size() uintptr
        
            // String returns a string representation of the type.
            // The string representation may use shortened package names
            // (e.g., base64 instead of "encoding/base64") and is not
            // guaranteed to be unique among types. To test for type identity,
            // compare the Types directly.
            String() string
        
            // Kind returns the specific kind of this type.
            Kind() Kind
        
            // Implements reports whether the type implements the interface type u.
            Implements(u Type) bool
        
            // AssignableTo reports whether a value of the type is assignable to type u.
            AssignableTo(u Type) bool
        
            // ConvertibleTo reports whether a value of the type is convertible to type u.
            // Even if ConvertibleTo returns true, the conversion may still panic.
            // For example, a slice of type []T is convertible to *[N]T,
            // but the conversion will panic if its length is less than N.
            ConvertibleTo(u Type) bool
        
            // Comparable reports whether values of this type are comparable.
            // Even if Comparable returns true, the comparison may still panic.
            // For example, values of interface type are comparable,
            // but the comparison will panic if their dynamic type is not comparable.
            Comparable() bool
        
            // Bits returns the size of the type in bits.
            // It panics if the type's Kind is not one of the
            // sized or unsized Int, Uint, Float, or Complex kinds.
            Bits() int
        
            // ChanDir returns a channel type's direction.
            // It panics if the type's Kind is not Chan.
            ChanDir() ChanDir
        
            // IsVariadic reports whether a function type's final input parameter
            // is a "..." parameter. If so, t.In(t.NumIn() - 1) returns the parameter's
            // implicit actual type []T.
            //
            // For concreteness, if t represents func(x int, y ... float64), then
            //
            //	t.NumIn() == 2
            //	t.In(0) is the reflect.Type for "int"
            //	t.In(1) is the reflect.Type for "[]float64"
            //	t.IsVariadic() == true
            //
            // IsVariadic panics if the type's Kind is not Func.
            IsVariadic() bool
        
            // Elem returns a type's element type.
            // It panics if the type's Kind is not Array, Chan, Map, Pointer, or Slice.
            Elem() Type
        
            // Field returns a struct type's i'th field.
            // It panics if the type's Kind is not Struct.
            // It panics if i is not in the range [0, NumField()).
            Field(i int) StructField
        
            // FieldByIndex returns the nested field corresponding
            // to the index sequence. It is equivalent to calling Field
            // successively for each index i.
            // It panics if the type's Kind is not Struct.
            FieldByIndex(index []int) StructField
        
            // FieldByName returns the struct field with the given name
            // and a boolean indicating if the field was found.
            // If the returned field is promoted from an embedded struct,
            // then Offset in the returned StructField is the offset in
            // the embedded struct.
            FieldByName(name string) (StructField, bool)
        
            // FieldByNameFunc returns the struct field with a name
            // that satisfies the match function and a boolean indicating if
            // the field was found.
            //
            // FieldByNameFunc considers the fields in the struct itself
            // and then the fields in any embedded structs, in breadth first order,
            // stopping at the shallowest nesting depth containing one or more
            // fields satisfying the match function. If multiple fields at that depth
            // satisfy the match function, they cancel each other
            // and FieldByNameFunc returns no match.
            // This behavior mirrors Go's handling of name lookup in
            // structs containing embedded fields.
            //
            // If the returned field is promoted from an embedded struct,
            // then Offset in the returned StructField is the offset in
            // the embedded struct.
            FieldByNameFunc(match func(string) bool) (StructField, bool)
        
            // In returns the type of a function type's i'th input parameter.
            // It panics if the type's Kind is not Func.
            // It panics if i is not in the range [0, NumIn()).
            In(i int) Type
        
            // Key returns a map type's key type.
            // It panics if the type's Kind is not Map.
            Key() Type
        
            // Len returns an array type's length.
            // It panics if the type's Kind is not Array.
            Len() int
        
            // NumField returns a struct type's field count.
            // It panics if the type's Kind is not Struct.
            NumField() int
        
            // NumIn returns a function type's input parameter count.
            // It panics if the type's Kind is not Func.
            NumIn() int
        
            // NumOut returns a function type's output parameter count.
            // It panics if the type's Kind is not Func.
            NumOut() int
        
            // Out returns the type of a function type's i'th output parameter.
            // It panics if the type's Kind is not Func.
            // It panics if i is not in the range [0, NumOut()).
            Out(i int) Type
            // contains filtered or unexported methods
        }

        func ArrayOf

        func ArrayOf(length int, elem Type) Type

        ArrayOf returns the array type with the given length and element type. For example, if t represents int, ArrayOf(5, t) represents [5]int.

        If the resulting type would be larger than the available address space, ArrayOf panics.

        func ChanOf

        func ChanOf(dir ChanDir, t Type) Type

        ChanOf returns the channel type with the given direction and element type. For example, if t represents int, ChanOf(RecvDir, t) represents <-chan int.

        The gc runtime imposes a limit of 64 kB on channel element types. If t's size is equal to or exceeds this limit, ChanOf panics.

        func FuncOf

        func FuncOf(in, out []Type, variadic bool) Type

        FuncOf returns the function type with the given argument and result types. For example if k represents int and e represents string, FuncOf([]Type{k}, []Type{e}, false) represents func(int) string.

        The variadic argument controls whether the function is variadic. FuncOf panics if the in[len(in)-1] does not represent a slice and variadic is true.

        func MapOf

        func MapOf(key, elem Type) Type

        MapOf returns the map type with the given key and element types. For example, if k represents int and e represents string, MapOf(k, e) represents map[int]string.

        If the key type is not a valid map key type (that is, if it does not implement Go's == operator), MapOf panics.

        func PointerTo

        func PointerTo(t Type) Type

        PointerTo returns the pointer type with element t. For example, if t represents type Foo, PointerTo(t) represents *Foo.

        func PtrTo

        func PtrTo(t Type) Type

        PtrTo returns the pointer type with element t. For example, if t represents type Foo, PtrTo(t) represents *Foo.

        PtrTo is the old spelling of PointerTo. The two functions behave identically.

        Deprecated: Superseded by PointerTo.

        func SliceOf

        func SliceOf(t Type) Type

        SliceOf returns the slice type with element type t. For example, if t represents int, SliceOf(t) represents []int.

        func StructOf

        func StructOf(fields []StructField) Type

        StructOf returns the struct type containing fields. The Offset and Index fields are ignored and computed as they would be by the compiler.

        StructOf currently does not support promoted methods of embedded fields and panics if passed unexported StructFields.

        Example

        Code:

        typ := reflect.StructOf([]reflect.StructField{
            {
                Name: "Height",
                Type: reflect.TypeOf(float64(0)),
                Tag:  `json:"height"`,
            },
            {
                Name: "Age",
                Type: reflect.TypeOf(int(0)),
                Tag:  `json:"age"`,
            },
        })
        
        v := reflect.New(typ).Elem()
        v.Field(0).SetFloat(0.4)
        v.Field(1).SetInt(2)
        s := v.Addr().Interface()
        
        w := new(bytes.Buffer)
        if err := json.NewEncoder(w).Encode(s); err != nil {
            panic(err)
        }
        
        fmt.Printf("value: %+v\n", s)
        fmt.Printf("json:  %s", w.Bytes())
        
        r := bytes.NewReader([]byte(`{"height":1.5,"age":10}`))
        if err := json.NewDecoder(r).Decode(s); err != nil {
            panic(err)
        }
        fmt.Printf("value: %+v\n", s)
        
        

        Output:

        value: &{Height:0.4 Age:2}
        json:  {"height":0.4,"age":2}
        value: &{Height:1.5 Age:10}
        

        func TypeFor

        func TypeFor[T any]() Type

        TypeFor returns the Type that represents the type argument T.

        func TypeOf

        func TypeOf(i any) Type

        TypeOf returns the reflection Type that represents the dynamic type of i. If i is a nil interface value, TypeOf returns nil.

        Example

        Code:

        // As interface types are only used for static typing, a
        // common idiom to find the reflection Type for an interface
        // type Foo is to use a *Foo value.
        writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()
        
        fileType := reflect.TypeOf((*os.File)(nil))
        fmt.Println(fileType.Implements(writerType))
        
        

        Output:

        true
        

        type Value

        Value is the reflection interface to a Go value.

        Not all methods apply to all kinds of values. Restrictions, if any, are noted in the documentation for each method. Use the Kind method to find out the kind of value before calling kind-specific methods. Calling a method inappropriate to the kind of type causes a run time panic.

        The zero Value represents no value. Its IsValid method returns false, its Kind method returns Invalid, its String method returns "<invalid Value>", and all other methods panic. Most functions and methods never return an invalid value. If one does, its documentation states the conditions explicitly.

        A Value can be used concurrently by multiple goroutines provided that the underlying Go value can be used concurrently for the equivalent direct operations.

        To compare two Values, compare the results of the Interface method. Using == on two Values does not compare the underlying values they represent.

        type Value struct {
            // contains filtered or unexported fields
        }
        

        func Append

        func Append(s Value, x ...Value) Value

        Append appends the values x to a slice s and returns the resulting slice. As in Go, each x's value must be assignable to the slice's element type.

        func AppendSlice

        func AppendSlice(s, t Value) Value

        AppendSlice appends a slice t to a slice s and returns the resulting slice. The slices s and t must have the same element type.

        func Indirect

        func Indirect(v Value) Value

        Indirect returns the value that v points to. If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v.

        func MakeChan

        func MakeChan(typ Type, buffer int) Value

        MakeChan creates a new channel with the specified type and buffer size.

        func MakeFunc

        func MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value

        MakeFunc returns a new function of the given Type that wraps the function fn. When called, that new function does the following:

        • converts its arguments to a slice of Values.
        • runs results := fn(args).
        • returns the results as a slice of Values, one per formal result.

        The implementation fn can assume that the argument Value slice has the number and type of arguments given by typ. If typ describes a variadic function, the final Value is itself a slice representing the variadic arguments, as in the body of a variadic function. The result Value slice returned by fn must have the number and type of results given by typ.

        The Value.Call method allows the caller to invoke a typed function in terms of Values; in contrast, MakeFunc allows the caller to implement a typed function in terms of Values.

        The Examples section of the documentation includes an illustration of how to use MakeFunc to build a swap function for different types.

        Example

        Code:

        // swap is the implementation passed to MakeFunc.
        // It must work in terms of reflect.Values so that it is possible
        // to write code without knowing beforehand what the types
        // will be.
        swap := func(in []reflect.Value) []reflect.Value {
            return []reflect.Value{in[1], in[0]}
        }
        
        // makeSwap expects fptr to be a pointer to a nil function.
        // It sets that pointer to a new function created with MakeFunc.
        // When the function is invoked, reflect turns the arguments
        // into Values, calls swap, and then turns swap's result slice
        // into the values returned by the new function.
        makeSwap := func(fptr any) {
            // fptr is a pointer to a function.
            // Obtain the function value itself (likely nil) as a reflect.Value
            // so that we can query its type and then set the value.
            fn := reflect.ValueOf(fptr).Elem()
        
            // Make a function of the right type.
            v := reflect.MakeFunc(fn.Type(), swap)
        
            // Assign it to the value fn represents.
            fn.Set(v)
        }
        
        // Make and call a swap function for ints.
        var intSwap func(int, int) (int, int)
        makeSwap(&intSwap)
        fmt.Println(intSwap(0, 1))
        
        // Make and call a swap function for float64s.
        var floatSwap func(float64, float64) (float64, float64)
        makeSwap(&floatSwap)
        fmt.Println(floatSwap(2.72, 3.14))
        
        

        Output:

        1 0
        3.14 2.72
        

        func MakeMap

        func MakeMap(typ Type) Value

        MakeMap creates a new map with the specified type.

        func MakeMapWithSize

        func MakeMapWithSize(typ Type, n int) Value

        MakeMapWithSize creates a new map with the specified type and initial space for approximately n elements.

        func MakeSlice

        func MakeSlice(typ Type, len, cap int) Value

        MakeSlice creates a new zero-initialized slice value for the specified slice type, length, and capacity.

        func New

        func New(typ Type) Value

        New returns a Value representing a pointer to a new zero value for the specified type. That is, the returned Value's Type is PointerTo(typ).

        func NewAt

        func NewAt(typ Type, p unsafe.Pointer) Value

        NewAt returns a Value representing a pointer to a value of the specified type, using p as that pointer.

        func Select

        func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool)

        Select executes a select operation described by the list of cases. Like the Go select statement, it blocks until at least one of the cases can proceed, makes a uniform pseudo-random choice, and then executes that case. It returns the index of the chosen case and, if that case was a receive operation, the value received and a boolean indicating whether the value corresponds to a send on the channel (as opposed to a zero value received because the channel is closed). Select supports a maximum of 65536 cases.

        func ValueOf

        func ValueOf(i any) Value

        ValueOf returns a new Value initialized to the concrete value stored in the interface i. ValueOf(nil) returns the zero Value.

        func Zero

        func Zero(typ Type) Value

        Zero returns a Value representing the zero value for the specified type. The result is different from the zero value of the Value struct, which represents no value at all. For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0. The returned value is neither addressable nor settable.

        func (Value) Addr

        func (v Value) Addr() Value

        Addr returns a pointer value representing the address of v. It panics if Value.CanAddr returns false. Addr is typically used to obtain a pointer to a struct field or slice element in order to call a method that requires a pointer receiver.

        func (Value) Bool

        func (v Value) Bool() bool

        Bool returns v's underlying value. It panics if v's kind is not Bool.

        func (Value) Bytes

        func (v Value) Bytes() []byte

        Bytes returns v's underlying value. It panics if v's underlying value is not a slice of bytes or an addressable array of bytes.

        func (Value) Call

        func (v Value) Call(in []Value) []Value

        Call calls the function v with the input arguments in. For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]). Call panics if v's Kind is not Func. It returns the output results as Values. As in Go, each input argument must be assignable to the type of the function's corresponding input parameter. If v is a variadic function, Call creates the variadic slice parameter itself, copying in the corresponding values.

        func (Value) CallSlice

        func (v Value) CallSlice(in []Value) []Value

        CallSlice calls the variadic function v with the input arguments in, assigning the slice in[len(in)-1] to v's final variadic argument. For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...). CallSlice panics if v's Kind is not Func or if v is not variadic. It returns the output results as Values. As in Go, each input argument must be assignable to the type of the function's corresponding input parameter.

        func (Value) CanAddr

        func (v Value) CanAddr() bool

        CanAddr reports whether the value's address can be obtained with Value.Addr. Such values are called addressable. A value is addressable if it is an element of a slice, an element of an addressable array, a field of an addressable struct, or the result of dereferencing a pointer. If CanAddr returns false, calling Value.Addr will panic.

        func (Value) CanComplex

        func (v Value) CanComplex() bool

        CanComplex reports whether Value.Complex can be used without panicking.

        func (Value) CanConvert

        func (v Value) CanConvert(t Type) bool

        CanConvert reports whether the value v can be converted to type t. If v.CanConvert(t) returns true then v.Convert(t) will not panic.

        func (Value) CanFloat

        func (v Value) CanFloat() bool

        CanFloat reports whether Value.Float can be used without panicking.

        func (Value) CanInt

        func (v Value) CanInt() bool

        CanInt reports whether Int can be used without panicking.

        func (Value) CanInterface

        func (v Value) CanInterface() bool

        CanInterface reports whether Value.Interface can be used without panicking.

        func (Value) CanSet

        func (v Value) CanSet() bool

        CanSet reports whether the value of v can be changed. A Value can be changed only if it is addressable and was not obtained by the use of unexported struct fields. If CanSet returns false, calling Value.Set or any type-specific setter (e.g., Value.SetBool, Value.SetInt) will panic.

        func (Value) CanUint

        func (v Value) CanUint() bool

        CanUint reports whether Value.Uint can be used without panicking.

        func (Value) Cap

        func (v Value) Cap() int

        Cap returns v's capacity. It panics if v's Kind is not Array, Chan, Slice or pointer to Array.

        func (Value) Clear

        func (v Value) Clear()

        Clear clears the contents of a map or zeros the contents of a slice.

        It panics if v's Kind is not Map or Slice.

        func (Value) Close

        func (v Value) Close()

        Close closes the channel v. It panics if v's Kind is not Chan or v is a receive-only channel.

        func (Value) Comparable

        func (v Value) Comparable() bool

        Comparable reports whether the value v is comparable. If the type of v is an interface, this checks the dynamic type. If this reports true then v.Interface() == x will not panic for any x, nor will v.Equal(u) for any Value u.

        func (Value) Complex

        func (v Value) Complex() complex128

        Complex returns v's underlying value, as a complex128. It panics if v's Kind is not Complex64 or Complex128

        func (Value) Convert

        func (v Value) Convert(t Type) Value

        Convert returns the value v converted to type t. If the usual Go conversion rules do not allow conversion of the value v to type t, or if converting v to type t panics, Convert panics.

        func (Value) Elem

        func (v Value) Elem() Value

        Elem returns the value that the interface v contains or that the pointer v points to. It panics if v's Kind is not Interface or Pointer. It returns the zero Value if v is nil.

        func (Value) Equal

        func (v Value) Equal(u Value) bool

        Equal reports true if v is equal to u. For two invalid values, Equal will report true. For an interface value, Equal will compare the value within the interface. Otherwise, If the values have different types, Equal will report false. Otherwise, for arrays and structs Equal will compare each element in order, and report false if it finds non-equal elements. During all comparisons, if values of the same type are compared, and the type is not comparable, Equal will panic.

        func (Value) Field

        func (v Value) Field(i int) Value

        Field returns the i'th field of the struct v. It panics if v's Kind is not Struct or i is out of range.

        func (Value) FieldByIndex

        func (v Value) FieldByIndex(index []int) Value

        FieldByIndex returns the nested field corresponding to index. It panics if evaluation requires stepping through a nil pointer or a field that is not a struct.

        Example

        Code:

        // This example shows a case in which the name of a promoted field
        // is hidden by another field: FieldByName will not work, so
        // FieldByIndex must be used instead.
        type user struct {
            firstName string
            lastName  string
        }
        
        type data struct {
            user
            firstName string
            lastName  string
        }
        
        u := data{
            user:      user{"Embedded John", "Embedded Doe"},
            firstName: "John",
            lastName:  "Doe",
        }
        
        s := reflect.ValueOf(u).FieldByIndex([]int{0, 1})
        fmt.Println("embedded last name:", s)
        
        

        Output:

        embedded last name: Embedded Doe
        

        func (Value) FieldByIndexErr

        func (v Value) FieldByIndexErr(index []int) (Value, error)

        FieldByIndexErr returns the nested field corresponding to index. It returns an error if evaluation requires stepping through a nil pointer, but panics if it must step through a field that is not a struct.

        func (Value) FieldByName

        func (v Value) FieldByName(name string) Value

        FieldByName returns the struct field with the given name. It returns the zero Value if no field was found. It panics if v's Kind is not Struct.

        Example

        Code:

        type user struct {
            firstName string
            lastName  string
        }
        u := user{firstName: "John", lastName: "Doe"}
        s := reflect.ValueOf(u)
        
        fmt.Println("Name:", s.FieldByName("firstName"))
        

        Output:

        Name: John
        

        func (Value) FieldByNameFunc

        func (v Value) FieldByNameFunc(match func(string) bool) Value

        FieldByNameFunc returns the struct field with a name that satisfies the match function. It panics if v's Kind is not Struct. It returns the zero Value if no field was found.

        func (Value) Float

        func (v Value) Float() float64

        Float returns v's underlying value, as a float64. It panics if v's Kind is not Float32 or Float64

        func (Value) Grow

        func (v Value) Grow(n int)

        Grow increases the slice's capacity, if necessary, to guarantee space for another n elements. After Grow(n), at least n elements can be appended to the slice without another allocation.

        It panics if v's Kind is not a Slice or if n is negative or too large to allocate the memory.

        func (Value) Index

        func (v Value) Index(i int) Value

        Index returns v's i'th element. It panics if v's Kind is not Array, Slice, or String or i is out of range.

        func (Value) Int

        func (v Value) Int() int64

        Int returns v's underlying value, as an int64. It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.

        func (Value) Interface

        func (v Value) Interface() (i any)

        Interface returns v's current value as an interface{}. It is equivalent to:

        var i interface{} = (v's underlying value)
        

        It panics if the Value was obtained by accessing unexported struct fields.

        func (Value) InterfaceData

        func (v Value) InterfaceData() [2]uintptr

        InterfaceData returns a pair of unspecified uintptr values. It panics if v's Kind is not Interface.

        In earlier versions of Go, this function returned the interface's value as a uintptr pair. As of Go 1.4, the implementation of interface values precludes any defined use of InterfaceData.

        Deprecated: The memory representation of interface values is not compatible with InterfaceData.

        func (Value) IsNil

        func (v Value) IsNil() bool

        IsNil reports whether its argument v is nil. The argument must be a chan, func, interface, map, pointer, or slice value; if it is not, IsNil panics. Note that IsNil is not always equivalent to a regular comparison with nil in Go. For example, if v was created by calling ValueOf with an uninitialized interface variable i, i==nil will be true but v.IsNil will panic as v will be the zero Value.

        func (Value) IsValid

        func (v Value) IsValid() bool

        IsValid reports whether v represents a value. It returns false if v is the zero Value. If IsValid returns false, all other methods except String panic. Most functions and methods never return an invalid Value. If one does, its documentation states the conditions explicitly.

        func (Value) IsZero

        func (v Value) IsZero() bool

        IsZero reports whether v is the zero value for its type. It panics if the argument is invalid.

        func (Value) Kind

        func (v Value) Kind() Kind

        Kind returns v's Kind. If v is the zero Value (Value.IsValid returns false), Kind returns Invalid.

        func (Value) Len

        func (v Value) Len() int

        Len returns v's length. It panics if v's Kind is not Array, Chan, Map, Slice, String, or pointer to Array.

        func (Value) MapIndex

        func (v Value) MapIndex(key Value) Value

        MapIndex returns the value associated with key in the map v. It panics if v's Kind is not Map. It returns the zero Value if key is not found in the map or if v represents a nil map. As in Go, the key's value must be assignable to the map's key type.

        func (Value) MapKeys

        func (v Value) MapKeys() []Value

        MapKeys returns a slice containing all the keys present in the map, in unspecified order. It panics if v's Kind is not Map. It returns an empty slice if v represents a nil map.

        func (Value) MapRange

        func (v Value) MapRange() *MapIter

        MapRange returns a range iterator for a map. It panics if v's Kind is not Map.

        Call MapIter.Next to advance the iterator, and MapIter.Key/MapIter.Value to access each entry. MapIter.Next returns false when the iterator is exhausted. MapRange follows the same iteration semantics as a range statement.

        Example:

        iter := reflect.ValueOf(m).MapRange()
        for iter.Next() {
        	k := iter.Key()
        	v := iter.Value()
        	...
        }
        

        func (Value) Method

        func (v Value) Method(i int) Value

        Method returns a function value corresponding to v's i'th method. The arguments to a Call on the returned function should not include a receiver; the returned function will always use v as the receiver. Method panics if i is out of range or if v is a nil interface value.

        func (Value) MethodByName

        func (v Value) MethodByName(name string) Value

        MethodByName returns a function value corresponding to the method of v with the given name. The arguments to a Call on the returned function should not include a receiver; the returned function will always use v as the receiver. It returns the zero Value if no method was found.

        func (Value) NumField

        func (v Value) NumField() int

        NumField returns the number of fields in the struct v. It panics if v's Kind is not Struct.

        func (Value) NumMethod

        func (v Value) NumMethod() int

        NumMethod returns the number of methods in the value's method set.

        For a non-interface type, it returns the number of exported methods.

        For an interface type, it returns the number of exported and unexported methods.

        func (Value) OverflowComplex

        func (v Value) OverflowComplex(x complex128) bool

        OverflowComplex reports whether the complex128 x cannot be represented by v's type. It panics if v's Kind is not Complex64 or Complex128.

        func (Value) OverflowFloat

        func (v Value) OverflowFloat(x float64) bool

        OverflowFloat reports whether the float64 x cannot be represented by v's type. It panics if v's Kind is not Float32 or Float64.

        func (Value) OverflowInt

        func (v Value) OverflowInt(x int64) bool

        OverflowInt reports whether the int64 x cannot be represented by v's type. It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.

        func (Value) OverflowUint

        func (v Value) OverflowUint(x uint64) bool

        OverflowUint reports whether the uint64 x cannot be represented by v's type. It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.

        func (Value) Pointer

        func (v Value) Pointer() uintptr

        Pointer returns v's value as a uintptr. It panics if v's Kind is not Chan, Func, Map, Pointer, Slice, or UnsafePointer.

        If v's Kind is Func, the returned pointer is an underlying code pointer, but not necessarily enough to identify a single function uniquely. The only guarantee is that the result is zero if and only if v is a nil func Value.

        If v's Kind is Slice, the returned pointer is to the first element of the slice. If the slice is nil the returned value is 0. If the slice is empty but non-nil the return value is non-zero.

        It's preferred to use uintptr(Value.UnsafePointer()) to get the equivalent result.

        func (Value) Recv

        func (v Value) Recv() (x Value, ok bool)

        Recv receives and returns a value from the channel v. It panics if v's Kind is not Chan. The receive blocks until a value is ready. The boolean value ok is true if the value x corresponds to a send on the channel, false if it is a zero value received because the channel is closed.

        func (Value) Send

        func (v Value) Send(x Value)

        Send sends x on the channel v. It panics if v's kind is not Chan or if x's type is not the same type as v's element type. As in Go, x's value must be assignable to the channel's element type.

        func (Value) Set

        func (v Value) Set(x Value)

        Set assigns x to the value v. It panics if Value.CanSet returns false. As in Go, x's value must be assignable to v's type and must not be derived from an unexported field.

        func (Value) SetBool

        func (v Value) SetBool(x bool)

        SetBool sets v's underlying value. It panics if v's Kind is not Bool or if Value.CanSet returns false.

        func (Value) SetBytes

        func (v Value) SetBytes(x []byte)

        SetBytes sets v's underlying value. It panics if v's underlying value is not a slice of bytes.

        func (Value) SetCap

        func (v Value) SetCap(n int)

        SetCap sets v's capacity to n. It panics if v's Kind is not Slice or if n is smaller than the length or greater than the capacity of the slice.

        func (Value) SetComplex

        func (v Value) SetComplex(x complex128)

        SetComplex sets v's underlying value to x. It panics if v's Kind is not Complex64 or Complex128, or if Value.CanSet returns false.

        func (Value) SetFloat

        func (v Value) SetFloat(x float64)

        SetFloat sets v's underlying value to x. It panics if v's Kind is not Float32 or Float64, or if Value.CanSet returns false.

        func (Value) SetInt

        func (v Value) SetInt(x int64)

        SetInt sets v's underlying value to x. It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if Value.CanSet returns false.

        func (Value) SetIterKey

        func (v Value) SetIterKey(iter *MapIter)

        SetIterKey assigns to v the key of iter's current map entry. It is equivalent to v.Set(iter.Key()), but it avoids allocating a new Value. As in Go, the key must be assignable to v's type and must not be derived from an unexported field.

        func (Value) SetIterValue

        func (v Value) SetIterValue(iter *MapIter)

        SetIterValue assigns to v the value of iter's current map entry. It is equivalent to v.Set(iter.Value()), but it avoids allocating a new Value. As in Go, the value must be assignable to v's type and must not be derived from an unexported field.

        func (Value) SetLen

        func (v Value) SetLen(n int)

        SetLen sets v's length to n. It panics if v's Kind is not Slice or if n is negative or greater than the capacity of the slice.

        func (Value) SetMapIndex

        func (v Value) SetMapIndex(key, elem Value)

        SetMapIndex sets the element associated with key in the map v to elem. It panics if v's Kind is not Map. If elem is the zero Value, SetMapIndex deletes the key from the map. Otherwise if v holds a nil map, SetMapIndex will panic. As in Go, key's elem must be assignable to the map's key type, and elem's value must be assignable to the map's elem type.

        func (Value) SetPointer

        func (v Value) SetPointer(x unsafe.Pointer)

        SetPointer sets the unsafe.Pointer value v to x. It panics if v's Kind is not UnsafePointer.

        func (Value) SetString

        func (v Value) SetString(x string)

        SetString sets v's underlying value to x. It panics if v's Kind is not String or if Value.CanSet returns false.

        func (Value) SetUint

        func (v Value) SetUint(x uint64)

        SetUint sets v's underlying value to x. It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if Value.CanSet returns false.

        func (Value) SetZero

        func (v Value) SetZero()

        SetZero sets v to be the zero value of v's type. It panics if Value.CanSet returns false.

        func (Value) Slice

        func (v Value) Slice(i, j int) Value

        Slice returns v[i:j]. It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array, or if the indexes are out of bounds.

        func (Value) Slice3

        func (v Value) Slice3(i, j, k int) Value

        Slice3 is the 3-index form of the slice operation: it returns v[i:j:k]. It panics if v's Kind is not Array or Slice, or if v is an unaddressable array, or if the indexes are out of bounds.

        func (Value) String

        func (v Value) String() string

        String returns the string v's underlying value, as a string. String is a special case because of Go's String method convention. Unlike the other getters, it does not panic if v's Kind is not String. Instead, it returns a string of the form "<T value>" where T is v's type. The fmt package treats Values specially. It does not call their String method implicitly but instead prints the concrete values they hold.

        func (Value) TryRecv

        func (v Value) TryRecv() (x Value, ok bool)

        TryRecv attempts to receive a value from the channel v but will not block. It panics if v's Kind is not Chan. If the receive delivers a value, x is the transferred value and ok is true. If the receive cannot finish without blocking, x is the zero Value and ok is false. If the channel is closed, x is the zero value for the channel's element type and ok is false.

        func (Value) TrySend

        func (v Value) TrySend(x Value) bool

        TrySend attempts to send x on the channel v but will not block. It panics if v's Kind is not Chan. It reports whether the value was sent. As in Go, x's value must be assignable to the channel's element type.

        func (Value) Type

        func (v Value) Type() Type

        Type returns v's type.

        func (Value) Uint

        func (v Value) Uint() uint64

        Uint returns v's underlying value, as a uint64. It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.

        func (Value) UnsafeAddr

        func (v Value) UnsafeAddr() uintptr

        UnsafeAddr returns a pointer to v's data, as a uintptr. It panics if v is not addressable.

        It's preferred to use uintptr(Value.Addr().UnsafePointer()) to get the equivalent result.

        func (Value) UnsafePointer

        func (v Value) UnsafePointer() unsafe.Pointer

        UnsafePointer returns v's value as a unsafe.Pointer. It panics if v's Kind is not Chan, Func, Map, Pointer, Slice, or UnsafePointer.

        If v's Kind is Func, the returned pointer is an underlying code pointer, but not necessarily enough to identify a single function uniquely. The only guarantee is that the result is zero if and only if v is a nil func Value.

        If v's Kind is Slice, the returned pointer is to the first element of the slice. If the slice is nil the returned value is nil. If the slice is empty but non-nil the return value is non-nil.

        type ValueError

        A ValueError occurs when a Value method is invoked on a Value that does not support it. Such cases are documented in the description of each method.

        type ValueError struct {
            Method string
            Kind   Kind
        }
        

        func (*ValueError) Error

        func (e *ValueError) Error() string

        Bugs

        • FieldByName and related functions consider struct field names to be equal if the names are equal, even if they are unexported names originating in different packages. The practical effect of this is that the result of t.FieldByName("x") is not well defined if the struct type t contains multiple fields named x (embedded from different packages). FieldByName may return one of the fields named x or may report that there are none. See https://golang.org/issue/4876 for more details.

        Subdirectories

        Name Synopsis
        ..
        regexp - Go Documentation Server
        ...

        Package regexp

        Overview ▾

        Package regexp implements regular expression search.

        The syntax of the regular expressions accepted is the same general syntax used by Perl, Python, and other languages. More precisely, it is the syntax accepted by RE2 and described at https://golang.org/s/re2syntax, except for \C. For an overview of the syntax, see the regexp/syntax package.

        The regexp implementation provided by this package is guaranteed to run in time linear in the size of the input. (This is a property not guaranteed by most open source implementations of regular expressions.) For more information about this property, see

        https://swtch.com/~rsc/regexp/regexp1.html
        

        or any book about automata theory.

        All characters are UTF-8-encoded code points. Following utf8.DecodeRune, each byte of an invalid UTF-8 sequence is treated as if it encoded utf8.RuneError (U+FFFD).

        There are 16 methods of Regexp that match a regular expression and identify the matched text. Their names are matched by this regular expression:

        Find(All)?(String)?(Submatch)?(Index)?
        

        If 'All' is present, the routine matches successive non-overlapping matches of the entire expression. Empty matches abutting a preceding match are ignored. The return value is a slice containing the successive return values of the corresponding non-'All' routine. These routines take an extra integer argument, n. If n >= 0, the function returns at most n matches/submatches; otherwise, it returns all of them.

        If 'String' is present, the argument is a string; otherwise it is a slice of bytes; return values are adjusted as appropriate.

        If 'Submatch' is present, the return value is a slice identifying the successive submatches of the expression. Submatches are matches of parenthesized subexpressions (also known as capturing groups) within the regular expression, numbered from left to right in order of opening parenthesis. Submatch 0 is the match of the entire expression, submatch 1 is the match of the first parenthesized subexpression, and so on.

        If 'Index' is present, matches and submatches are identified by byte index pairs within the input string: result[2*n:2*n+2] identifies the indexes of the nth submatch. The pair for n==0 identifies the match of the entire expression. If 'Index' is not present, the match is identified by the text of the match/submatch. If an index is negative or text is nil, it means that subexpression did not match any string in the input. For 'String' versions an empty string means either no match or an empty match.

        There is also a subset of the methods that can be applied to text read from a RuneReader:

        MatchReader, FindReaderIndex, FindReaderSubmatchIndex
        

        This set may grow. Note that regular expression matches may need to examine text beyond the text returned by a match, so the methods that match text from a RuneReader may read arbitrarily far into the input before returning.

        (There are a few other methods that do not match this pattern.)

        Example

        Code:

        // Compile the expression once, usually at init time.
        // Use raw strings to avoid having to quote the backslashes.
        var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)
        
        fmt.Println(validID.MatchString("adam[23]"))
        fmt.Println(validID.MatchString("eve[7]"))
        fmt.Println(validID.MatchString("Job[48]"))
        fmt.Println(validID.MatchString("snakey"))
        

        Output:

        true
        true
        false
        false
        

        Index ▾

        func Match(pattern string, b []byte) (matched bool, err error)
        func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)
        func MatchString(pattern string, s string) (matched bool, err error)
        func QuoteMeta(s string) string
        type Regexp
            func Compile(expr string) (*Regexp, error)
            func CompilePOSIX(expr string) (*Regexp, error)
            func MustCompile(str string) *Regexp
            func MustCompilePOSIX(str string) *Regexp
            func (re *Regexp) Copy() *Regexp
            func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte
            func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte
            func (re *Regexp) Find(b []byte) []byte
            func (re *Regexp) FindAll(b []byte, n int) [][]byte
            func (re *Regexp) FindAllIndex(b []byte, n int) [][]int
            func (re *Regexp) FindAllString(s string, n int) []string
            func (re *Regexp) FindAllStringIndex(s string, n int) [][]int
            func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string
            func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int
            func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte
            func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int
            func (re *Regexp) FindIndex(b []byte) (loc []int)
            func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int)
            func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []int
            func (re *Regexp) FindString(s string) string
            func (re *Regexp) FindStringIndex(s string) (loc []int)
            func (re *Regexp) FindStringSubmatch(s string) []string
            func (re *Regexp) FindStringSubmatchIndex(s string) []int
            func (re *Regexp) FindSubmatch(b []byte) [][]byte
            func (re *Regexp) FindSubmatchIndex(b []byte) []int
            func (re *Regexp) LiteralPrefix() (prefix string, complete bool)
            func (re *Regexp) Longest()
            func (re *Regexp) MarshalText() ([]byte, error)
            func (re *Regexp) Match(b []byte) bool
            func (re *Regexp) MatchReader(r io.RuneReader) bool
            func (re *Regexp) MatchString(s string) bool
            func (re *Regexp) NumSubexp() int
            func (re *Regexp) ReplaceAll(src, repl []byte) []byte
            func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte
            func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte
            func (re *Regexp) ReplaceAllLiteralString(src, repl string) string
            func (re *Regexp) ReplaceAllString(src, repl string) string
            func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string
            func (re *Regexp) Split(s string, n int) []string
            func (re *Regexp) String() string
            func (re *Regexp) SubexpIndex(name string) int
            func (re *Regexp) SubexpNames() []string
            func (re *Regexp) UnmarshalText(text []byte) error

        Package files

        backtrack.go exec.go onepass.go regexp.go

        func Match

        func Match(pattern string, b []byte) (matched bool, err error)

        Match reports whether the byte slice b contains any match of the regular expression pattern. More complicated queries need to use Compile and the full Regexp interface.

        Example

        Code:

        matched, err := regexp.Match(`foo.*`, []byte(`seafood`))
        fmt.Println(matched, err)
        matched, err = regexp.Match(`bar.*`, []byte(`seafood`))
        fmt.Println(matched, err)
        matched, err = regexp.Match(`a(b`, []byte(`seafood`))
        fmt.Println(matched, err)
        
        

        Output:

        true <nil>
        false <nil>
        false error parsing regexp: missing closing ): `a(b`
        

        func MatchReader

        func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)

        MatchReader reports whether the text returned by the RuneReader contains any match of the regular expression pattern. More complicated queries need to use Compile and the full Regexp interface.

        func MatchString

        func MatchString(pattern string, s string) (matched bool, err error)

        MatchString reports whether the string s contains any match of the regular expression pattern. More complicated queries need to use Compile and the full Regexp interface.

        Example

        Code:

        matched, err := regexp.MatchString(`foo.*`, "seafood")
        fmt.Println(matched, err)
        matched, err = regexp.MatchString(`bar.*`, "seafood")
        fmt.Println(matched, err)
        matched, err = regexp.MatchString(`a(b`, "seafood")
        fmt.Println(matched, err)
        

        Output:

        true <nil>
        false <nil>
        false error parsing regexp: missing closing ): `a(b`
        

        func QuoteMeta

        func QuoteMeta(s string) string

        QuoteMeta returns a string that escapes all regular expression metacharacters inside the argument text; the returned string is a regular expression matching the literal text.

        Example

        Code:

        fmt.Println(regexp.QuoteMeta(`Escaping symbols like: .+*?()|[]{}^$`))
        

        Output:

        Escaping symbols like: \.\+\*\?\(\)\|\[\]\{\}\^\$
        

        type Regexp

        Regexp is the representation of a compiled regular expression. A Regexp is safe for concurrent use by multiple goroutines, except for configuration methods, such as Regexp.Longest.

        type Regexp struct {
            // contains filtered or unexported fields
        }
        

        func Compile

        func Compile(expr string) (*Regexp, error)

        Compile parses a regular expression and returns, if successful, a Regexp object that can be used to match against text.

        When matching against text, the regexp returns a match that begins as early as possible in the input (leftmost), and among those it chooses the one that a backtracking search would have found first. This so-called leftmost-first matching is the same semantics that Perl, Python, and other implementations use, although this package implements it without the expense of backtracking. For POSIX leftmost-longest matching, see CompilePOSIX.

        func CompilePOSIX

        func CompilePOSIX(expr string) (*Regexp, error)

        CompilePOSIX is like Compile but restricts the regular expression to POSIX ERE (egrep) syntax and changes the match semantics to leftmost-longest.

        That is, when matching against text, the regexp returns a match that begins as early as possible in the input (leftmost), and among those it chooses a match that is as long as possible. This so-called leftmost-longest matching is the same semantics that early regular expression implementations used and that POSIX specifies.

        However, there can be multiple leftmost-longest matches, with different submatch choices, and here this package diverges from POSIX. Among the possible leftmost-longest matches, this package chooses the one that a backtracking search would have found first, while POSIX specifies that the match be chosen to maximize the length of the first subexpression, then the second, and so on from left to right. The POSIX rule is computationally prohibitive and not even well-defined. See https://swtch.com/~rsc/regexp/regexp2.html#posix for details.

        func MustCompile

        func MustCompile(str string) *Regexp

        MustCompile is like Compile but panics if the expression cannot be parsed. It simplifies safe initialization of global variables holding compiled regular expressions.

        func MustCompilePOSIX

        func MustCompilePOSIX(str string) *Regexp

        MustCompilePOSIX is like CompilePOSIX but panics if the expression cannot be parsed. It simplifies safe initialization of global variables holding compiled regular expressions.

        func (*Regexp) Copy

        func (re *Regexp) Copy() *Regexp

        Copy returns a new Regexp object copied from re. Calling Regexp.Longest on one copy does not affect another.

        Deprecated: In earlier releases, when using a Regexp in multiple goroutines, giving each goroutine its own copy helped to avoid lock contention. As of Go 1.12, using Copy is no longer necessary to avoid lock contention. Copy may still be appropriate if the reason for its use is to make two copies with different Regexp.Longest settings.

        func (*Regexp) Expand

        func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte

        Expand appends template to dst and returns the result; during the append, Expand replaces variables in the template with corresponding matches drawn from src. The match slice should have been returned by Regexp.FindSubmatchIndex.

        In the template, a variable is denoted by a substring of the form $name or ${name}, where name is a non-empty sequence of letters, digits, and underscores. A purely numeric name like $1 refers to the submatch with the corresponding index; other names refer to capturing parentheses named with the (?P<name>...) syntax. A reference to an out of range or unmatched index or a name that is not present in the regular expression is replaced with an empty slice.

        In the $name form, name is taken to be as long as possible: $1x is equivalent to ${1x}, not ${1}x, and, $10 is equivalent to ${10}, not ${1}0.

        To insert a literal $ in the output, use $$ in the template.

        Example

        Code:

        content := []byte(`
            # comment line
            option1: value1
            option2: value2
        
            # another comment line
            option3: value3
        `)
        
        // Regex pattern captures "key: value" pair from the content.
        pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
        
        // Template to convert "key: value" to "key=value" by
        // referencing the values captured by the regex pattern.
        template := []byte("$key=$value\n")
        
        result := []byte{}
        
        // For each match of the regex in the content.
        for _, submatches := range pattern.FindAllSubmatchIndex(content, -1) {
            // Apply the captured submatches to the template and append the output
            // to the result.
            result = pattern.Expand(result, template, content, submatches)
        }
        fmt.Println(string(result))
        

        Output:

        option1=value1
        option2=value2
        option3=value3
        

        func (*Regexp) ExpandString

        func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte

        ExpandString is like Regexp.Expand but the template and source are strings. It appends to and returns a byte slice in order to give the calling code control over allocation.

        Example

        Code:

        content := `
            # comment line
            option1: value1
            option2: value2
        
            # another comment line
            option3: value3
        `
        
        // Regex pattern captures "key: value" pair from the content.
        pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
        
        // Template to convert "key: value" to "key=value" by
        // referencing the values captured by the regex pattern.
        template := "$key=$value\n"
        
        result := []byte{}
        
        // For each match of the regex in the content.
        for _, submatches := range pattern.FindAllStringSubmatchIndex(content, -1) {
            // Apply the captured submatches to the template and append the output
            // to the result.
            result = pattern.ExpandString(result, template, content, submatches)
        }
        fmt.Println(string(result))
        

        Output:

        option1=value1
        option2=value2
        option3=value3
        

        func (*Regexp) Find

        func (re *Regexp) Find(b []byte) []byte

        Find returns a slice holding the text of the leftmost match in b of the regular expression. A return value of nil indicates no match.

        Example

        Code:

        re := regexp.MustCompile(`foo.?`)
        fmt.Printf("%q\n", re.Find([]byte(`seafood fool`)))
        
        

        Output:

        "food"
        

        func (*Regexp) FindAll

        func (re *Regexp) FindAll(b []byte, n int) [][]byte

        FindAll is the 'All' version of Find; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

        Example

        Code:

        re := regexp.MustCompile(`foo.?`)
        fmt.Printf("%q\n", re.FindAll([]byte(`seafood fool`), -1))
        
        

        Output:

        ["food" "fool"]
        

        func (*Regexp) FindAllIndex

        func (re *Regexp) FindAllIndex(b []byte, n int) [][]int

        FindAllIndex is the 'All' version of Regexp.FindIndex; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

        Example

        Code:

        content := []byte("London")
        re := regexp.MustCompile(`o.`)
        fmt.Println(re.FindAllIndex(content, 1))
        fmt.Println(re.FindAllIndex(content, -1))
        

        Output:

        [[1 3]]
        [[1 3] [4 6]]
        

        func (*Regexp) FindAllString

        func (re *Regexp) FindAllString(s string, n int) []string

        FindAllString is the 'All' version of Regexp.FindString; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

        Example

        Code:

        re := regexp.MustCompile(`a.`)
        fmt.Println(re.FindAllString("paranormal", -1))
        fmt.Println(re.FindAllString("paranormal", 2))
        fmt.Println(re.FindAllString("graal", -1))
        fmt.Println(re.FindAllString("none", -1))
        

        Output:

        [ar an al]
        [ar an]
        [aa]
        []
        

        func (*Regexp) FindAllStringIndex

        func (re *Regexp) FindAllStringIndex(s string, n int) [][]int

        FindAllStringIndex is the 'All' version of Regexp.FindStringIndex; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

        func (*Regexp) FindAllStringSubmatch

        func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string

        FindAllStringSubmatch is the 'All' version of Regexp.FindStringSubmatch; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

        Example

        Code:

        re := regexp.MustCompile(`a(x*)b`)
        fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-", -1))
        fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-", -1))
        fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-axb-", -1))
        fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-ab-", -1))
        

        Output:

        [["ab" ""]]
        [["axxb" "xx"]]
        [["ab" ""] ["axb" "x"]]
        [["axxb" "xx"] ["ab" ""]]
        

        func (*Regexp) FindAllStringSubmatchIndex

        func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int

        FindAllStringSubmatchIndex is the 'All' version of Regexp.FindStringSubmatchIndex; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

        Example

        Code:

        re := regexp.MustCompile(`a(x*)b`)
        // Indices:
        //    01234567   012345678
        //    -ab-axb-   -axxb-ab-
        fmt.Println(re.FindAllStringSubmatchIndex("-ab-", -1))
        fmt.Println(re.FindAllStringSubmatchIndex("-axxb-", -1))
        fmt.Println(re.FindAllStringSubmatchIndex("-ab-axb-", -1))
        fmt.Println(re.FindAllStringSubmatchIndex("-axxb-ab-", -1))
        fmt.Println(re.FindAllStringSubmatchIndex("-foo-", -1))
        

        Output:

        [[1 3 2 2]]
        [[1 5 2 4]]
        [[1 3 2 2] [4 7 5 6]]
        [[1 5 2 4] [6 8 7 7]]
        []
        

        func (*Regexp) FindAllSubmatch

        func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte

        FindAllSubmatch is the 'All' version of Regexp.FindSubmatch; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

        Example

        Code:

        re := regexp.MustCompile(`foo(.?)`)
        fmt.Printf("%q\n", re.FindAllSubmatch([]byte(`seafood fool`), -1))
        
        

        Output:

        [["food" "d"] ["fool" "l"]]
        

        func (*Regexp) FindAllSubmatchIndex

        func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int

        FindAllSubmatchIndex is the 'All' version of Regexp.FindSubmatchIndex; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.

        Example

        Code:

        content := []byte(`
            # comment line
            option1: value1
            option2: value2
        `)
        // Regex pattern captures "key: value" pair from the content.
        pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
        allIndexes := pattern.FindAllSubmatchIndex(content, -1)
        for _, loc := range allIndexes {
            fmt.Println(loc)
            fmt.Println(string(content[loc[0]:loc[1]]))
            fmt.Println(string(content[loc[2]:loc[3]]))
            fmt.Println(string(content[loc[4]:loc[5]]))
        }
        

        Output:

        [18 33 18 25 27 33]
        option1: value1
        option1
        value1
        [35 50 35 42 44 50]
        option2: value2
        option2
        value2
        

        func (*Regexp) FindIndex

        func (re *Regexp) FindIndex(b []byte) (loc []int)

        FindIndex returns a two-element slice of integers defining the location of the leftmost match in b of the regular expression. The match itself is at b[loc[0]:loc[1]]. A return value of nil indicates no match.

        Example

        Code:

        content := []byte(`
            # comment line
            option1: value1
            option2: value2
        `)
        // Regex pattern captures "key: value" pair from the content.
        pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
        
        loc := pattern.FindIndex(content)
        fmt.Println(loc)
        fmt.Println(string(content[loc[0]:loc[1]]))
        

        Output:

        [18 33]
        option1: value1
        

        func (*Regexp) FindReaderIndex

        func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int)

        FindReaderIndex returns a two-element slice of integers defining the location of the leftmost match of the regular expression in text read from the io.RuneReader. The match text was found in the input stream at byte offset loc[0] through loc[1]-1. A return value of nil indicates no match.

        func (*Regexp) FindReaderSubmatchIndex

        func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []int

        FindReaderSubmatchIndex returns a slice holding the index pairs identifying the leftmost match of the regular expression of text read by the io.RuneReader, and the matches, if any, of its subexpressions, as defined by the 'Submatch' and 'Index' descriptions in the package comment. A return value of nil indicates no match.

        func (*Regexp) FindString

        func (re *Regexp) FindString(s string) string

        FindString returns a string holding the text of the leftmost match in s of the regular expression. If there is no match, the return value is an empty string, but it will also be empty if the regular expression successfully matches an empty string. Use Regexp.FindStringIndex or Regexp.FindStringSubmatch if it is necessary to distinguish these cases.

        Example

        Code:

        re := regexp.MustCompile(`foo.?`)
        fmt.Printf("%q\n", re.FindString("seafood fool"))
        fmt.Printf("%q\n", re.FindString("meat"))
        

        Output:

        "food"
        ""
        

        func (*Regexp) FindStringIndex

        func (re *Regexp) FindStringIndex(s string) (loc []int)

        FindStringIndex returns a two-element slice of integers defining the location of the leftmost match in s of the regular expression. The match itself is at s[loc[0]:loc[1]]. A return value of nil indicates no match.

        Example

        Code:

        re := regexp.MustCompile(`ab?`)
        fmt.Println(re.FindStringIndex("tablett"))
        fmt.Println(re.FindStringIndex("foo") == nil)
        

        Output:

        [1 3]
        true
        

        func (*Regexp) FindStringSubmatch

        func (re *Regexp) FindStringSubmatch(s string) []string

        FindStringSubmatch returns a slice of strings holding the text of the leftmost match of the regular expression in s and the matches, if any, of its subexpressions, as defined by the 'Submatch' description in the package comment. A return value of nil indicates no match.

        Example

        Code:

        re := regexp.MustCompile(`a(x*)b(y|z)c`)
        fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))
        fmt.Printf("%q\n", re.FindStringSubmatch("-abzc-"))
        

        Output:

        ["axxxbyc" "xxx" "y"]
        ["abzc" "" "z"]
        

        func (*Regexp) FindStringSubmatchIndex

        func (re *Regexp) FindStringSubmatchIndex(s string) []int

        FindStringSubmatchIndex returns a slice holding the index pairs identifying the leftmost match of the regular expression in s and the matches, if any, of its subexpressions, as defined by the 'Submatch' and 'Index' descriptions in the package comment. A return value of nil indicates no match.

        func (*Regexp) FindSubmatch

        func (re *Regexp) FindSubmatch(b []byte) [][]byte

        FindSubmatch returns a slice of slices holding the text of the leftmost match of the regular expression in b and the matches, if any, of its subexpressions, as defined by the 'Submatch' descriptions in the package comment. A return value of nil indicates no match.

        Example

        Code:

        re := regexp.MustCompile(`foo(.?)`)
        fmt.Printf("%q\n", re.FindSubmatch([]byte(`seafood fool`)))
        
        

        Output:

        ["food" "d"]
        

        func (*Regexp) FindSubmatchIndex

        func (re *Regexp) FindSubmatchIndex(b []byte) []int

        FindSubmatchIndex returns a slice holding the index pairs identifying the leftmost match of the regular expression in b and the matches, if any, of its subexpressions, as defined by the 'Submatch' and 'Index' descriptions in the package comment. A return value of nil indicates no match.

        Example

        Code:

        re := regexp.MustCompile(`a(x*)b`)
        // Indices:
        //    01234567   012345678
        //    -ab-axb-   -axxb-ab-
        fmt.Println(re.FindSubmatchIndex([]byte("-ab-")))
        fmt.Println(re.FindSubmatchIndex([]byte("-axxb-")))
        fmt.Println(re.FindSubmatchIndex([]byte("-ab-axb-")))
        fmt.Println(re.FindSubmatchIndex([]byte("-axxb-ab-")))
        fmt.Println(re.FindSubmatchIndex([]byte("-foo-")))
        

        Output:

        [1 3 2 2]
        [1 5 2 4]
        [1 3 2 2]
        [1 5 2 4]
        []
        

        func (*Regexp) LiteralPrefix

        func (re *Regexp) LiteralPrefix() (prefix string, complete bool)

        LiteralPrefix returns a literal string that must begin any match of the regular expression re. It returns the boolean true if the literal string comprises the entire regular expression.

        func (*Regexp) Longest

        func (re *Regexp) Longest()

        Longest makes future searches prefer the leftmost-longest match. That is, when matching against text, the regexp returns a match that begins as early as possible in the input (leftmost), and among those it chooses a match that is as long as possible. This method modifies the Regexp and may not be called concurrently with any other methods.

        Example

        Code:

        re := regexp.MustCompile(`a(|b)`)
        fmt.Println(re.FindString("ab"))
        re.Longest()
        fmt.Println(re.FindString("ab"))
        

        Output:

        a
        ab
        

        func (*Regexp) MarshalText

        func (re *Regexp) MarshalText() ([]byte, error)

        MarshalText implements encoding.TextMarshaler. The output matches that of calling the Regexp.String method.

        Note that the output is lossy in some cases: This method does not indicate POSIX regular expressions (i.e. those compiled by calling CompilePOSIX), or those for which the Regexp.Longest method has been called.

        func (*Regexp) Match

        func (re *Regexp) Match(b []byte) bool

        Match reports whether the byte slice b contains any match of the regular expression re.

        Example

        Code:

        re := regexp.MustCompile(`foo.?`)
        fmt.Println(re.Match([]byte(`seafood fool`)))
        fmt.Println(re.Match([]byte(`something else`)))
        
        

        Output:

        true
        false
        

        func (*Regexp) MatchReader

        func (re *Regexp) MatchReader(r io.RuneReader) bool

        MatchReader reports whether the text returned by the io.RuneReader contains any match of the regular expression re.

        func (*Regexp) MatchString

        func (re *Regexp) MatchString(s string) bool

        MatchString reports whether the string s contains any match of the regular expression re.

        Example

        Code:

        re := regexp.MustCompile(`(gopher){2}`)
        fmt.Println(re.MatchString("gopher"))
        fmt.Println(re.MatchString("gophergopher"))
        fmt.Println(re.MatchString("gophergophergopher"))
        

        Output:

        false
        true
        true
        

        func (*Regexp) NumSubexp

        func (re *Regexp) NumSubexp() int

        NumSubexp returns the number of parenthesized subexpressions in this Regexp.

        Example

        Code:

        re0 := regexp.MustCompile(`a.`)
        fmt.Printf("%d\n", re0.NumSubexp())
        
        re := regexp.MustCompile(`(.*)((a)b)(.*)a`)
        fmt.Println(re.NumSubexp())
        

        Output:

        0
        4
        

        func (*Regexp) ReplaceAll

        func (re *Regexp) ReplaceAll(src, repl []byte) []byte

        ReplaceAll returns a copy of src, replacing matches of the Regexp with the replacement text repl. Inside repl, $ signs are interpreted as in Regexp.Expand.

        Example

        Code:

        re := regexp.MustCompile(`a(x*)b`)
        fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("T")))
        fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1")))
        fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
        fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
        
        re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
        fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
        fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
        
        

        Output:

        -T-T-
        --xx-
        ---
        -W-xxW-
        --xx-
        -W-xxW-
        

        func (*Regexp) ReplaceAllFunc

        func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte

        ReplaceAllFunc returns a copy of src in which all matches of the Regexp have been replaced by the return value of function repl applied to the matched byte slice. The replacement returned by repl is substituted directly, without using Regexp.Expand.

        func (*Regexp) ReplaceAllLiteral

        func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte

        ReplaceAllLiteral returns a copy of src, replacing matches of the Regexp with the replacement bytes repl. The replacement repl is substituted directly, without using Regexp.Expand.

        func (*Regexp) ReplaceAllLiteralString

        func (re *Regexp) ReplaceAllLiteralString(src, repl string) string

        ReplaceAllLiteralString returns a copy of src, replacing matches of the Regexp with the replacement string repl. The replacement repl is substituted directly, without using Regexp.Expand.

        Example

        Code:

        re := regexp.MustCompile(`a(x*)b`)
        fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "T"))
        fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "$1"))
        fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "${1}"))
        

        Output:

        -T-T-
        -$1-$1-
        -${1}-${1}-
        

        func (*Regexp) ReplaceAllString

        func (re *Regexp) ReplaceAllString(src, repl string) string

        ReplaceAllString returns a copy of src, replacing matches of the Regexp with the replacement string repl. Inside repl, $ signs are interpreted as in Regexp.Expand.

        Example

        Code:

        re := regexp.MustCompile(`a(x*)b`)
        fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))
        fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
        fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
        fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
        
        re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
        fmt.Printf("%s\n", re2.ReplaceAllString("-ab-axxb-", "$1W"))
        fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
        
        

        Output:

        -T-T-
        --xx-
        ---
        -W-xxW-
        --xx-
        -W-xxW-
        

        func (*Regexp) ReplaceAllStringFunc

        func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string

        ReplaceAllStringFunc returns a copy of src in which all matches of the Regexp have been replaced by the return value of function repl applied to the matched substring. The replacement returned by repl is substituted directly, without using Regexp.Expand.

        Example

        Code:

        re := regexp.MustCompile(`[^aeiou]`)
        fmt.Println(re.ReplaceAllStringFunc("seafood fool", strings.ToUpper))
        

        Output:

        SeaFooD FooL
        

        func (*Regexp) Split

        func (re *Regexp) Split(s string, n int) []string

        Split slices s into substrings separated by the expression and returns a slice of the substrings between those expression matches.

        The slice returned by this method consists of all the substrings of s not contained in the slice returned by Regexp.FindAllString. When called on an expression that contains no metacharacters, it is equivalent to strings.SplitN.

        Example:

        s := regexp.MustCompile("a*").Split("abaabaccadaaae", 5)
        // s: ["", "b", "b", "c", "cadaaae"]
        

        The count determines the number of substrings to return:

        n > 0: at most n substrings; the last substring will be the unsplit remainder.
        n == 0: the result is nil (zero substrings)
        n < 0: all substrings
        

        Example

        Code:

        a := regexp.MustCompile(`a`)
        fmt.Println(a.Split("banana", -1))
        fmt.Println(a.Split("banana", 0))
        fmt.Println(a.Split("banana", 1))
        fmt.Println(a.Split("banana", 2))
        zp := regexp.MustCompile(`z+`)
        fmt.Println(zp.Split("pizza", -1))
        fmt.Println(zp.Split("pizza", 0))
        fmt.Println(zp.Split("pizza", 1))
        fmt.Println(zp.Split("pizza", 2))
        

        Output:

        [b n n ]
        []
        [banana]
        [b nana]
        [pi a]
        []
        [pizza]
        [pi a]
        

        func (*Regexp) String

        func (re *Regexp) String() string

        String returns the source text used to compile the regular expression.

        func (*Regexp) SubexpIndex

        func (re *Regexp) SubexpIndex(name string) int

        SubexpIndex returns the index of the first subexpression with the given name, or -1 if there is no subexpression with that name.

        Note that multiple subexpressions can be written using the same name, as in (?P<bob>a+)(?P<bob>b+), which declares two subexpressions named "bob". In this case, SubexpIndex returns the index of the leftmost such subexpression in the regular expression.

        Example

        Code:

        re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
        fmt.Println(re.MatchString("Alan Turing"))
        matches := re.FindStringSubmatch("Alan Turing")
        lastIndex := re.SubexpIndex("last")
        fmt.Printf("last => %d\n", lastIndex)
        fmt.Println(matches[lastIndex])
        

        Output:

        true
        last => 2
        Turing
        

        func (*Regexp) SubexpNames

        func (re *Regexp) SubexpNames() []string

        SubexpNames returns the names of the parenthesized subexpressions in this Regexp. The name for the first sub-expression is names[1], so that if m is a match slice, the name for m[i] is SubexpNames()[i]. Since the Regexp as a whole cannot be named, names[0] is always the empty string. The slice should not be modified.

        Example

        Code:

        re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
        fmt.Println(re.MatchString("Alan Turing"))
        fmt.Printf("%q\n", re.SubexpNames())
        reversed := fmt.Sprintf("${%s} ${%s}", re.SubexpNames()[2], re.SubexpNames()[1])
        fmt.Println(reversed)
        fmt.Println(re.ReplaceAllString("Alan Turing", reversed))
        

        Output:

        true
        ["" "first" "last"]
        ${last} ${first}
        Turing Alan
        

        func (*Regexp) UnmarshalText

        func (re *Regexp) UnmarshalText(text []byte) error

        UnmarshalText implements encoding.TextUnmarshaler by calling Compile on the encoded value.

        Subdirectories

        Name Synopsis
        ..
        syntax Package syntax parses regular expressions into parse trees and compiles parse trees into programs.
        syntax - Go Documentation Server
        ...

        Package syntax

        import "regexp/syntax"
        Overview
        Index

        Overview ▾

        Package syntax parses regular expressions into parse trees and compiles parse trees into programs. Most clients of regular expressions will use the facilities of package regexp (such as Compile and Match) instead of this package.

        Syntax

        The regular expression syntax understood by this package when parsing with the Perl flag is as follows. Parts of the syntax can be disabled by passing alternate flags to Parse.

        Single characters:

        .              any character, possibly including newline (flag s=true)
        [xyz]          character class
        [^xyz]         negated character class
        \d             Perl character class
        \D             negated Perl character class
        [[:alpha:]]    ASCII character class
        [[:^alpha:]]   negated ASCII character class
        \pN            Unicode character class (one-letter name)
        \p{Greek}      Unicode character class
        \PN            negated Unicode character class (one-letter name)
        \P{Greek}      negated Unicode character class
        

        Composites:

        xy             x followed by y
        x|y            x or y (prefer x)
        

        Repetitions:

        x*             zero or more x, prefer more
        x+             one or more x, prefer more
        x?             zero or one x, prefer one
        x{n,m}         n or n+1 or ... or m x, prefer more
        x{n,}          n or more x, prefer more
        x{n}           exactly n x
        x*?            zero or more x, prefer fewer
        x+?            one or more x, prefer fewer
        x??            zero or one x, prefer zero
        x{n,m}?        n or n+1 or ... or m x, prefer fewer
        x{n,}?         n or more x, prefer fewer
        x{n}?          exactly n x
        

        Implementation restriction: The counting forms x{n,m}, x{n,}, and x{n} reject forms that create a minimum or maximum repetition count above 1000. Unlimited repetitions are not subject to this restriction.

        Grouping:

        (re)           numbered capturing group (submatch)
        (?P<name>re)   named & numbered capturing group (submatch)
        (?<name>re)    named & numbered capturing group (submatch)
        (?:re)         non-capturing group
        (?flags)       set flags within current group; non-capturing
        (?flags:re)    set flags during re; non-capturing
        
        Flag syntax is xyz (set) or -xyz (clear) or xy-z (set xy, clear z). The flags are:
        
        i              case-insensitive (default false)
        m              multi-line mode: ^ and $ match begin/end line in addition to begin/end text (default false)
        s              let . match \n (default false)
        U              ungreedy: swap meaning of x* and x*?, x+ and x+?, etc (default false)
        

        Empty strings:

        ^              at beginning of text or line (flag m=true)
        $              at end of text (like \z not \Z) or line (flag m=true)
        \A             at beginning of text
        \b             at ASCII word boundary (\w on one side and \W, \A, or \z on the other)
        \B             not at ASCII word boundary
        \z             at end of text
        

        Escape sequences:

        \a             bell (== \007)
        \f             form feed (== \014)
        \t             horizontal tab (== \011)
        \n             newline (== \012)
        \r             carriage return (== \015)
        \v             vertical tab character (== \013)
        \*             literal *, for any punctuation character *
        \123           octal character code (up to three digits)
        \x7F           hex character code (exactly two digits)
        \x{10FFFF}     hex character code
        \Q...\E        literal text ... even if ... has punctuation
        

        Character class elements:

        x              single character
        A-Z            character range (inclusive)
        \d             Perl character class
        [:foo:]        ASCII character class foo
        \p{Foo}        Unicode character class Foo
        \pF            Unicode character class F (one-letter name)
        

        Named character classes as character class elements:

        [\d]           digits (== \d)
        [^\d]          not digits (== \D)
        [\D]           not digits (== \D)
        [^\D]          not not digits (== \d)
        [[:name:]]     named ASCII class inside character class (== [:name:])
        [^[:name:]]    named ASCII class inside negated character class (== [:^name:])
        [\p{Name}]     named Unicode property inside character class (== \p{Name})
        [^\p{Name}]    named Unicode property inside negated character class (== \P{Name})
        

        Perl character classes (all ASCII-only):

        \d             digits (== [0-9])
        \D             not digits (== [^0-9])
        \s             whitespace (== [\t\n\f\r ])
        \S             not whitespace (== [^\t\n\f\r ])
        \w             word characters (== [0-9A-Za-z_])
        \W             not word characters (== [^0-9A-Za-z_])
        

        ASCII character classes:

        [[:alnum:]]    alphanumeric (== [0-9A-Za-z])
        [[:alpha:]]    alphabetic (== [A-Za-z])
        [[:ascii:]]    ASCII (== [\x00-\x7F])
        [[:blank:]]    blank (== [\t ])
        [[:cntrl:]]    control (== [\x00-\x1F\x7F])
        [[:digit:]]    digits (== [0-9])
        [[:graph:]]    graphical (== [!-~] == [A-Za-z0-9!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])
        [[:lower:]]    lower case (== [a-z])
        [[:print:]]    printable (== [ -~] == [ [:graph:]])
        [[:punct:]]    punctuation (== [!-/:-@[-`{-~])
        [[:space:]]    whitespace (== [\t\n\v\f\r ])
        [[:upper:]]    upper case (== [A-Z])
        [[:word:]]     word characters (== [0-9A-Za-z_])
        [[:xdigit:]]   hex digit (== [0-9A-Fa-f])
        

        Unicode character classes are those in unicode.Categories and unicode.Scripts.

        func IsWordChar

        func IsWordChar(r rune) bool

        IsWordChar reports whether r is considered a “word character” during the evaluation of the \b and \B zero-width assertions. These assertions are ASCII-only: the word characters are [A-Za-z0-9_].

        type EmptyOp

        An EmptyOp specifies a kind or mixture of zero-width assertions.

        type EmptyOp uint8
        const (
            EmptyBeginLine EmptyOp = 1 << iota
            EmptyEndLine
            EmptyBeginText
            EmptyEndText
            EmptyWordBoundary
            EmptyNoWordBoundary
        )

        func EmptyOpContext

        func EmptyOpContext(r1, r2 rune) EmptyOp

        EmptyOpContext returns the zero-width assertions satisfied at the position between the runes r1 and r2. Passing r1 == -1 indicates that the position is at the beginning of the text. Passing r2 == -1 indicates that the position is at the end of the text.

        type Error

        An Error describes a failure to parse a regular expression and gives the offending expression.

        type Error struct {
            Code ErrorCode
            Expr string
        }
        

        func (*Error) Error

        func (e *Error) Error() string

        type ErrorCode

        An ErrorCode describes a failure to parse a regular expression.

        type ErrorCode string
        const (
            // Unexpected error
            ErrInternalError ErrorCode = "regexp/syntax: internal error"
        
            // Parse errors
            ErrInvalidCharClass      ErrorCode = "invalid character class"
            ErrInvalidCharRange      ErrorCode = "invalid character class range"
            ErrInvalidEscape         ErrorCode = "invalid escape sequence"
            ErrInvalidNamedCapture   ErrorCode = "invalid named capture"
            ErrInvalidPerlOp         ErrorCode = "invalid or unsupported Perl syntax"
            ErrInvalidRepeatOp       ErrorCode = "invalid nested repetition operator"
            ErrInvalidRepeatSize     ErrorCode = "invalid repeat count"
            ErrInvalidUTF8           ErrorCode = "invalid UTF-8"
            ErrMissingBracket        ErrorCode = "missing closing ]"
            ErrMissingParen          ErrorCode = "missing closing )"
            ErrMissingRepeatArgument ErrorCode = "missing argument to repetition operator"
            ErrTrailingBackslash     ErrorCode = "trailing backslash at end of expression"
            ErrUnexpectedParen       ErrorCode = "unexpected )"
            ErrNestingDepth          ErrorCode = "expression nests too deeply"
            ErrLarge                 ErrorCode = "expression too large"
        )

        func (ErrorCode) String

        func (e ErrorCode) String() string

        type Flags

        Flags control the behavior of the parser and record information about regexp context.

        type Flags uint16
        const (
            FoldCase      Flags = 1 << iota // case-insensitive match
            Literal                         // treat pattern as literal string
            ClassNL                         // allow character classes like [^a-z] and [[:space:]] to match newline
            DotNL                           // allow . to match newline
            OneLine                         // treat ^ and $ as only matching at beginning and end of text
            NonGreedy                       // make repetition operators default to non-greedy
            PerlX                           // allow Perl extensions
            UnicodeGroups                   // allow \p{Han}, \P{Han} for Unicode group and negation
            WasDollar                       // regexp OpEndText was $, not \z
            Simple                          // regexp contains no counted repetition
        
            MatchNL = ClassNL | DotNL
        
            Perl        = ClassNL | OneLine | PerlX | UnicodeGroups // as close to Perl as possible
            POSIX Flags = 0                                         // POSIX syntax
        )

        type Inst

        An Inst is a single instruction in a regular expression program.

        type Inst struct {
            Op   InstOp
            Out  uint32 // all but InstMatch, InstFail
            Arg  uint32 // InstAlt, InstAltMatch, InstCapture, InstEmptyWidth
            Rune []rune
        }
        

        func (*Inst) MatchEmptyWidth

        func (i *Inst) MatchEmptyWidth(before rune, after rune) bool

        MatchEmptyWidth reports whether the instruction matches an empty string between the runes before and after. It should only be called when i.Op == InstEmptyWidth.

        func (*Inst) MatchRune

        func (i *Inst) MatchRune(r rune) bool

        MatchRune reports whether the instruction matches (and consumes) r. It should only be called when i.Op == InstRune.

        func (*Inst) MatchRunePos

        func (i *Inst) MatchRunePos(r rune) int

        MatchRunePos checks whether the instruction matches (and consumes) r. If so, MatchRunePos returns the index of the matching rune pair (or, when len(i.Rune) == 1, rune singleton). If not, MatchRunePos returns -1. MatchRunePos should only be called when i.Op == InstRune.

        func (*Inst) String

        func (i *Inst) String() string

        type InstOp

        An InstOp is an instruction opcode.

        type InstOp uint8
        const (
            InstAlt InstOp = iota
            InstAltMatch
            InstCapture
            InstEmptyWidth
            InstMatch
            InstFail
            InstNop
            InstRune
            InstRune1
            InstRuneAny
            InstRuneAnyNotNL
        )

        func (InstOp) String

        func (i InstOp) String() string

        type Op

        An Op is a single regular expression operator.

        type Op uint8
        const (
            OpNoMatch        Op = 1 + iota // matches no strings
            OpEmptyMatch                   // matches empty string
            OpLiteral                      // matches Runes sequence
            OpCharClass                    // matches Runes interpreted as range pair list
            OpAnyCharNotNL                 // matches any character except newline
            OpAnyChar                      // matches any character
            OpBeginLine                    // matches empty string at beginning of line
            OpEndLine                      // matches empty string at end of line
            OpBeginText                    // matches empty string at beginning of text
            OpEndText                      // matches empty string at end of text
            OpWordBoundary                 // matches word boundary `\b`
            OpNoWordBoundary               // matches word non-boundary `\B`
            OpCapture                      // capturing subexpression with index Cap, optional name Name
            OpStar                         // matches Sub[0] zero or more times
            OpPlus                         // matches Sub[0] one or more times
            OpQuest                        // matches Sub[0] zero or one times
            OpRepeat                       // matches Sub[0] at least Min times, at most Max (Max == -1 is no limit)
            OpConcat                       // matches concatenation of Subs
            OpAlternate                    // matches alternation of Subs
        )

        func (Op) String

        func (i Op) String() string

        type Prog

        A Prog is a compiled regular expression program.

        type Prog struct {
            Inst   []Inst
            Start  int // index of start instruction
            NumCap int // number of InstCapture insts in re
        }
        

        func Compile

        func Compile(re *Regexp) (*Prog, error)

        Compile compiles the regexp into a program to be executed. The regexp should have been simplified already (returned from re.Simplify).

        func (*Prog) Prefix

        func (p *Prog) Prefix() (prefix string, complete bool)

        Prefix returns a literal string that all matches for the regexp must start with. Complete is true if the prefix is the entire match.

        func (*Prog) StartCond

        func (p *Prog) StartCond() EmptyOp

        StartCond returns the leading empty-width conditions that must be true in any match. It returns ^EmptyOp(0) if no matches are possible.

        func (*Prog) String

        func (p *Prog) String() string

        type Regexp

        A Regexp is a node in a regular expression syntax tree.

        type Regexp struct {
            Op       Op // operator
            Flags    Flags
            Sub      []*Regexp  // subexpressions, if any
            Sub0     [1]*Regexp // storage for short Sub
            Rune     []rune     // matched runes, for OpLiteral, OpCharClass
            Rune0    [2]rune    // storage for short Rune
            Min, Max int        // min, max for OpRepeat
            Cap      int        // capturing index, for OpCapture
            Name     string     // capturing name, for OpCapture
        }
        

        func Parse

        func Parse(s string, flags Flags) (*Regexp, error)

        Parse parses a regular expression string s, controlled by the specified Flags, and returns a regular expression parse tree. The syntax is described in the top-level comment.

        func (*Regexp) CapNames

        func (re *Regexp) CapNames() []string

        CapNames walks the regexp to find the names of capturing groups.

        func (*Regexp) Equal

        func (x *Regexp) Equal(y *Regexp) bool

        Equal reports whether x and y have identical structure.

        func (*Regexp) MaxCap

        func (re *Regexp) MaxCap() int

        MaxCap walks the regexp to find the maximum capture index.

        func (*Regexp) Simplify

        func (re *Regexp) Simplify() *Regexp

        Simplify returns a regexp equivalent to re but without counted repetitions and with various other simplifications, such as rewriting /(?:a+)+/ to /a+/. The resulting regexp will execute correctly but its string representation will not produce the same parse tree, because capturing parentheses may have been duplicated or removed. For example, the simplified form for /(x){1,2}/ is /(x)(x)?/ but both parentheses capture as $1. The returned regexp may share structure with or be the original.

        func (*Regexp) String

        func (re *Regexp) String() string
        runtime - Go Documentation Server
        ...

        Package runtime

        Overview ▾

        Package runtime contains operations that interact with Go's runtime system, such as functions to control goroutines. It also includes the low-level type information used by the reflect package; see reflect's documentation for the programmable interface to the run-time type system.

        Environment Variables

        The following environment variables ($name or %name%, depending on the host operating system) control the run-time behavior of Go programs. The meanings and use may change from release to release.

        The GOGC variable sets the initial garbage collection target percentage. A collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. The default is GOGC=100. Setting GOGC=off disables the garbage collector entirely. runtime/debug.SetGCPercent allows changing this percentage at run time.

        The GOMEMLIMIT variable sets a soft memory limit for the runtime. This memory limit includes the Go heap and all other memory managed by the runtime, and excludes external memory sources such as mappings of the binary itself, memory managed in other languages, and memory held by the operating system on behalf of the Go program. GOMEMLIMIT is a numeric value in bytes with an optional unit suffix. The supported suffixes include B, KiB, MiB, GiB, and TiB. These suffixes represent quantities of bytes as defined by the IEC 80000-13 standard. That is, they are based on powers of two: KiB means 2^10 bytes, MiB means 2^20 bytes, and so on. The default setting is math.MaxInt64, which effectively disables the memory limit. runtime/debug.SetMemoryLimit allows changing this limit at run time.

        The GODEBUG variable controls debugging variables within the runtime. It is a comma-separated list of name=val pairs setting these named variables:

        allocfreetrace: setting allocfreetrace=1 causes every allocation to be
        profiled and a stack trace printed on each object's allocation and free.
        
        clobberfree: setting clobberfree=1 causes the garbage collector to
        clobber the memory content of an object with bad content when it frees
        the object.
        
        cpu.*: cpu.all=off disables the use of all optional instruction set extensions.
        cpu.extension=off disables use of instructions from the specified instruction set extension.
        extension is the lower case name for the instruction set extension such as sse41 or avx
        as listed in internal/cpu package. As an example cpu.avx=off disables runtime detection
        and thereby use of AVX instructions.
        
        cgocheck: setting cgocheck=0 disables all checks for packages
        using cgo to incorrectly pass Go pointers to non-Go code.
        Setting cgocheck=1 (the default) enables relatively cheap
        checks that may miss some errors. A more complete, but slow,
        cgocheck mode can be enabled using GOEXPERIMENT (which
        requires a rebuild), see https://pkg.go.dev/internal/goexperiment for details.
        
        disablethp: setting disablethp=1 on Linux disables transparent huge pages for the heap.
        It has no effect on other platforms. disablethp is meant for compatibility with versions
        of Go before 1.21, which stopped working around a Linux kernel default that can result
        in significant memory overuse. See https://go.dev/issue/64332. This setting will be
        removed in a future release, so operators should tweak their Linux configuration to suit
        their needs before then. See https://go.dev/doc/gc-guide#Linux_transparent_huge_pages.
        
        dontfreezetheworld: by default, the start of a fatal panic or throw
        "freezes the world", preempting all threads to stop all running
        goroutines, which makes it possible to traceback all goroutines, and
        keeps their state close to the point of panic. Setting
        dontfreezetheworld=1 disables this preemption, allowing goroutines to
        continue executing during panic processing. Note that goroutines that
        naturally enter the scheduler will still stop. This can be useful when
        debugging the runtime scheduler, as freezetheworld perturbs scheduler
        state and thus may hide problems.
        
        efence: setting efence=1 causes the allocator to run in a mode
        where each object is allocated on a unique page and addresses are
        never recycled.
        
        gccheckmark: setting gccheckmark=1 enables verification of the
        garbage collector's concurrent mark phase by performing a
        second mark pass while the world is stopped.  If the second
        pass finds a reachable object that was not found by concurrent
        mark, the garbage collector will panic.
        
        gcpacertrace: setting gcpacertrace=1 causes the garbage collector to
        print information about the internal state of the concurrent pacer.
        
        gcshrinkstackoff: setting gcshrinkstackoff=1 disables moving goroutines
        onto smaller stacks. In this mode, a goroutine's stack can only grow.
        
        gcstoptheworld: setting gcstoptheworld=1 disables concurrent garbage collection,
        making every garbage collection a stop-the-world event. Setting gcstoptheworld=2
        also disables concurrent sweeping after the garbage collection finishes.
        
        gctrace: setting gctrace=1 causes the garbage collector to emit a single line to standard
        error at each collection, summarizing the amount of memory collected and the
        length of the pause. The format of this line is subject to change. Included in
        the explanation below is also the relevant runtime/metrics metric for each field.
        Currently, it is:
        	gc # @#s #%: #+#+# ms clock, #+#/#/#+# ms cpu, #->#-># MB, # MB goal, # MB stacks, #MB globals, # P
        where the fields are as follows:
        	gc #         the GC number, incremented at each GC
        	@#s          time in seconds since program start
        	#%           percentage of time spent in GC since program start
        	#+...+#      wall-clock/CPU times for the phases of the GC
        	#->#-># MB   heap size at GC start, at GC end, and live heap, or /gc/scan/heap:bytes
        	# MB goal    goal heap size, or /gc/heap/goal:bytes
        	# MB stacks  estimated scannable stack size, or /gc/scan/stack:bytes
        	# MB globals scannable global size, or /gc/scan/globals:bytes
        	# P          number of processors used, or /sched/gomaxprocs:threads
        The phases are stop-the-world (STW) sweep termination, concurrent
        mark and scan, and STW mark termination. The CPU times
        for mark/scan are broken down in to assist time (GC performed in
        line with allocation), background GC time, and idle GC time.
        If the line ends with "(forced)", this GC was forced by a
        runtime.GC() call.
        
        harddecommit: setting harddecommit=1 causes memory that is returned to the OS to
        also have protections removed on it. This is the only mode of operation on Windows,
        but is helpful in debugging scavenger-related issues on other platforms. Currently,
        only supported on Linux.
        
        inittrace: setting inittrace=1 causes the runtime to emit a single line to standard
        error for each package with init work, summarizing the execution time and memory
        allocation. No information is printed for inits executed as part of plugin loading
        and for packages without both user defined and compiler generated init work.
        The format of this line is subject to change. Currently, it is:
        	init # @#ms, # ms clock, # bytes, # allocs
        where the fields are as follows:
        	init #      the package name
        	@# ms       time in milliseconds when the init started since program start
        	# clock     wall-clock time for package initialization work
        	# bytes     memory allocated on the heap
        	# allocs    number of heap allocations
        
        madvdontneed: setting madvdontneed=0 will use MADV_FREE
        instead of MADV_DONTNEED on Linux when returning memory to the
        kernel. This is more efficient, but means RSS numbers will
        drop only when the OS is under memory pressure. On the BSDs and
        Illumos/Solaris, setting madvdontneed=1 will use MADV_DONTNEED instead
        of MADV_FREE. This is less efficient, but causes RSS numbers to drop
        more quickly.
        
        memprofilerate: setting memprofilerate=X will update the value of runtime.MemProfileRate.
        When set to 0 memory profiling is disabled.  Refer to the description of
        MemProfileRate for the default value.
        
        pagetrace: setting pagetrace=/path/to/file will write out a trace of page events
        that can be viewed, analyzed, and visualized using the x/debug/cmd/pagetrace tool.
        Build your program with GOEXPERIMENT=pagetrace to enable this functionality. Do not
        enable this functionality if your program is a setuid binary as it introduces a security
        risk in that scenario. Currently not supported on Windows, plan9 or js/wasm. Setting this
        option for some applications can produce large traces, so use with care.
        
        panicnil: setting panicnil=1 disables the runtime error when calling panic with nil
        interface value or an untyped nil.
        
        runtimecontentionstacks: setting runtimecontentionstacks=1 enables inclusion of call stacks
        related to contention on runtime-internal locks in the "mutex" profile, subject to the
        MutexProfileFraction setting. When runtimecontentionstacks=0, contention on
        runtime-internal locks will report as "runtime._LostContendedRuntimeLock". When
        runtimecontentionstacks=1, the call stacks will correspond to the unlock call that released
        the lock. But instead of the value corresponding to the amount of contention that call
        stack caused, it corresponds to the amount of time the caller of unlock had to wait in its
        original call to lock. A future release is expected to align those and remove this setting.
        
        invalidptr: invalidptr=1 (the default) causes the garbage collector and stack
        copier to crash the program if an invalid pointer value (for example, 1)
        is found in a pointer-typed location. Setting invalidptr=0 disables this check.
        This should only be used as a temporary workaround to diagnose buggy code.
        The real fix is to not store integers in pointer-typed locations.
        
        sbrk: setting sbrk=1 replaces the memory allocator and garbage collector
        with a trivial allocator that obtains memory from the operating system and
        never reclaims any memory.
        
        scavtrace: setting scavtrace=1 causes the runtime to emit a single line to standard
        error, roughly once per GC cycle, summarizing the amount of work done by the
        scavenger as well as the total amount of memory returned to the operating system
        and an estimate of physical memory utilization. The format of this line is subject
        to change, but currently it is:
        	scav # KiB work (bg), # KiB work (eager), # KiB total, #% util
        where the fields are as follows:
        	# KiB work (bg)    the amount of memory returned to the OS in the background since
        	                   the last line
        	# KiB work (eager) the amount of memory returned to the OS eagerly since the last line
        	# KiB now          the amount of address space currently returned to the OS
        	#% util            the fraction of all unscavenged heap memory which is in-use
        If the line ends with "(forced)", then scavenging was forced by a
        debug.FreeOSMemory() call.
        
        scheddetail: setting schedtrace=X and scheddetail=1 causes the scheduler to emit
        detailed multiline info every X milliseconds, describing state of the scheduler,
        processors, threads and goroutines.
        
        schedtrace: setting schedtrace=X causes the scheduler to emit a single line to standard
        error every X milliseconds, summarizing the scheduler state.
        
        tracebackancestors: setting tracebackancestors=N extends tracebacks with the stacks at
        which goroutines were created, where N limits the number of ancestor goroutines to
        report. This also extends the information returned by runtime.Stack. Ancestor's goroutine
        IDs will refer to the ID of the goroutine at the time of creation; it's possible for this
        ID to be reused for another goroutine. Setting N to 0 will report no ancestry information.
        
        tracefpunwindoff: setting tracefpunwindoff=1 forces the execution tracer to
        use the runtime's default stack unwinder instead of frame pointer unwinding.
        This increases tracer overhead, but could be helpful as a workaround or for
        debugging unexpected regressions caused by frame pointer unwinding.
        
        traceadvanceperiod: the approximate period in nanoseconds between trace generations. Only
        applies if a program is built with GOEXPERIMENT=exectracer2. Used primarily for testing
        and debugging the execution tracer.
        
        asyncpreemptoff: asyncpreemptoff=1 disables signal-based
        asynchronous goroutine preemption. This makes some loops
        non-preemptible for long periods, which may delay GC and
        goroutine scheduling. This is useful for debugging GC issues
        because it also disables the conservative stack scanning used
        for asynchronously preempted goroutines.
        

        The net and net/http packages also refer to debugging variables in GODEBUG. See the documentation for those packages for details.

        The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously. There is no limit to the number of threads that can be blocked in system calls on behalf of Go code; those do not count against the GOMAXPROCS limit. This package's GOMAXPROCS function queries and changes the limit.

        The GORACE variable configures the race detector, for programs built using -race. See the Race Detector article for details.

        The GOTRACEBACK variable controls the amount of output generated when a Go program fails due to an unrecovered panic or an unexpected runtime condition. By default, a failure prints a stack trace for the current goroutine, eliding functions internal to the run-time system, and then exits with exit code 2. The failure prints stack traces for all goroutines if there is no current goroutine or the failure is internal to the run-time. GOTRACEBACK=none omits the goroutine stack traces entirely. GOTRACEBACK=single (the default) behaves as described above. GOTRACEBACK=all adds stack traces for all user-created goroutines. GOTRACEBACK=system is like “all” but adds stack frames for run-time functions and shows goroutines created internally by the run-time. GOTRACEBACK=crash is like “system” but crashes in an operating system-specific manner instead of exiting. For example, on Unix systems, the crash raises SIGABRT to trigger a core dump. GOTRACEBACK=wer is like “crash” but doesn't disable Windows Error Reporting (WER). For historical reasons, the GOTRACEBACK settings 0, 1, and 2 are synonyms for none, all, and system, respectively. The runtime/debug.SetTraceback function allows increasing the amount of output at run time, but it cannot reduce the amount below that specified by the environment variable.

        The GOARCH, GOOS, GOPATH, and GOROOT environment variables complete the set of Go environment variables. They influence the building of Go programs (see cmd/go and go/build). GOARCH, GOOS, and GOROOT are recorded at compile time and made available by constants or functions in this package, but they do not influence the execution of the run-time system.

        Security

        On Unix platforms, Go's runtime system behaves slightly differently when a binary is setuid/setgid or executed with setuid/setgid-like properties, in order to prevent dangerous behaviors. On Linux this is determined by checking for the AT_SECURE flag in the auxiliary vector, on the BSDs and Solaris/Illumos it is determined by checking the issetugid syscall, and on AIX it is determined by checking if the uid/gid match the effective uid/gid.

        When the runtime determines the binary is setuid/setgid-like, it does three main things:

        • The standard input/output file descriptors (0, 1, 2) are checked to be open. If any of them are closed, they are opened pointing at /dev/null.
        • The value of the GOTRACEBACK environment variable is set to 'none'.
        • When a signal is received that terminates the program, or the program encounters an unrecoverable panic that would otherwise override the value of GOTRACEBACK, the goroutine stack, registers, and other memory related information are omitted.

        Index ▾

        Constants
        Variables
        func BlockProfile(p []BlockProfileRecord) (n int, ok bool)
        func Breakpoint()
        func CPUProfile() []byte
        func Caller(skip int) (pc uintptr, file string, line int, ok bool)
        func Callers(skip int, pc []uintptr) int
        func GC()
        func GOMAXPROCS(n int) int
        func GOROOT() string
        func Goexit()
        func GoroutineProfile(p []StackRecord) (n int, ok bool)
        func Gosched()
        func KeepAlive(x any)
        func LockOSThread()
        func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool)
        func MutexProfile(p []BlockProfileRecord) (n int, ok bool)
        func NumCPU() int
        func NumCgoCall() int64
        func NumGoroutine() int
        func ReadMemStats(m *MemStats)
        func ReadTrace() []byte
        func SetBlockProfileRate(rate int)
        func SetCPUProfileRate(hz int)
        func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer)
        func SetFinalizer(obj any, finalizer any)
        func SetMutexProfileFraction(rate int) int
        func Stack(buf []byte, all bool) int
        func StartTrace() error
        func StopTrace()
        func ThreadCreateProfile(p []StackRecord) (n int, ok bool)
        func UnlockOSThread()
        func Version() string
        type BlockProfileRecord
        type Error
        type Frame
        type Frames
            func CallersFrames(callers []uintptr) *Frames
            func (ci *Frames) Next() (frame Frame, more bool)
        type Func
            func FuncForPC(pc uintptr) *Func
            func (f *Func) Entry() uintptr
            func (f *Func) FileLine(pc uintptr) (file string, line int)
            func (f *Func) Name() string
        type MemProfileRecord
            func (r *MemProfileRecord) InUseBytes() int64
            func (r *MemProfileRecord) InUseObjects() int64
            func (r *MemProfileRecord) Stack() []uintptr
        type MemStats
        type PanicNilError
            func (*PanicNilError) Error() string
            func (*PanicNilError) RuntimeError()
        type Pinner
            func (p *Pinner) Pin(pointer any)
            func (p *Pinner) Unpin()
        type StackRecord
            func (r *StackRecord) Stack() []uintptr
        type TypeAssertionError
            func (e *TypeAssertionError) Error() string
            func (*TypeAssertionError) RuntimeError()

        Examples

        Frames

        Package files

        alg.go arena.go asan0.go atomic_pointer.go cgo.go cgo_mmap.go cgo_sigaction.go cgocall.go cgocallback.go cgocheck.go chan.go checkptr.go compiler.go complex.go coro.go covercounter.go covermeta.go cpuflags.go cpuflags_amd64.go cpuprof.go cputicks.go create_file_unix.go debug.go debugcall.go debuglog.go debuglog_off.go defs_linux_amd64.go env_posix.go error.go exithook.go extern.go fastlog2.go fastlog2table.go fds_unix.go float.go hash64.go heapdump.go histogram.go iface.go lfstack.go lock_futex.go lockrank.go lockrank_off.go malloc.go map.go map_fast32.go map_fast64.go map_faststr.go mbarrier.go mbitmap.go mbitmap_allocheaders.go mcache.go mcentral.go mcheckmark.go mem.go mem_linux.go metrics.go mfinal.go mfixalloc.go mgc.go mgclimit.go mgcmark.go mgcpacer.go mgcscavenge.go mgcstack.go mgcsweep.go mgcwork.go mheap.go minmax.go mpagealloc.go mpagealloc_64bit.go mpagecache.go mpallocbits.go mprof.go mranges.go msan0.go msize_allocheaders.go mspanset.go mstats.go mwbbuf.go nbpipe_pipe2.go netpoll.go netpoll_epoll.go nonwindows_stub.go os_linux.go os_linux_generic.go os_linux_noauxv.go os_linux_x86.go os_nonopenbsd.go os_unix.go pagetrace_off.go panic.go pinner.go plugin.go preempt.go preempt_nonwindows.go print.go proc.go profbuf.go proflabel.go race0.go rand.go rdebug.go retry.go runtime.go runtime1.go runtime2.go runtime_boring.go rwmutex.go security_linux.go security_unix.go select.go sema.go signal_amd64.go signal_linux_amd64.go signal_unix.go sigqueue.go sigqueue_note.go sigtab_linux_generic.go sizeclasses.go slice.go softfloat64.go stack.go stkframe.go string.go stubs.go stubs2.go stubs3.go stubs_amd64.go stubs_linux.go symtab.go symtabinl.go sys_nonppc64x.go sys_x86.go tagptr.go tagptr_64bit.go test_amd64.go time.go time_nofake.go timeasm.go tls_stub.go trace2.go trace2buf.go trace2cpu.go trace2event.go trace2map.go trace2region.go trace2runtime.go trace2stack.go trace2status.go trace2string.go trace2time.go traceback.go type.go typekind.go unsafe.go utf8.go vdso_elf64.go vdso_linux.go vdso_linux_amd64.go write_err.go

        Constants

        Compiler is the name of the compiler toolchain that built the running binary. Known toolchains are:

        gc      Also known as cmd/compile.
        gccgo   The gccgo front end, part of the GCC compiler suite.
        
        const Compiler = "gc"

        GOARCH is the running program's architecture target: one of 386, amd64, arm, s390x, and so on.

        const GOARCH string = goarch.GOARCH

        GOOS is the running program's operating system target: one of darwin, freebsd, linux, and so on. To view possible combinations of GOOS and GOARCH, run "go tool dist list".

        const GOOS string = goos.GOOS

        Variables

        MemProfileRate controls the fraction of memory allocations that are recorded and reported in the memory profile. The profiler aims to sample an average of one allocation per MemProfileRate bytes allocated.

        To include every allocated block in the profile, set MemProfileRate to 1. To turn off profiling entirely, set MemProfileRate to 0.

        The tools that process the memory profiles assume that the profile rate is constant across the lifetime of the program and equal to the current value. Programs that change the memory profiling rate should do so just once, as early as possible in the execution of the program (for example, at the beginning of main).

        var MemProfileRate int = 512 * 1024

        func BlockProfile

        func BlockProfile(p []BlockProfileRecord) (n int, ok bool)

        BlockProfile returns n, the number of records in the current blocking profile. If len(p) >= n, BlockProfile copies the profile into p and returns n, true. If len(p) < n, BlockProfile does not change p and returns n, false.

        Most clients should use the runtime/pprof package or the testing package's -test.blockprofile flag instead of calling BlockProfile directly.

        func Breakpoint

        func Breakpoint()

        Breakpoint executes a breakpoint trap.

        func CPUProfile

        func CPUProfile() []byte

        CPUProfile panics. It formerly provided raw access to chunks of a pprof-format profile generated by the runtime. The details of generating that format have changed, so this functionality has been removed.

        Deprecated: Use the runtime/pprof package, or the handlers in the net/http/pprof package, or the testing package's -test.cpuprofile flag instead.

        func Caller

        func Caller(skip int) (pc uintptr, file string, line int, ok bool)

        Caller reports file and line number information about function invocations on the calling goroutine's stack. The argument skip is the number of stack frames to ascend, with 0 identifying the caller of Caller. (For historical reasons the meaning of skip differs between Caller and Callers.) The return values report the program counter, file name, and line number within the file of the corresponding call. The boolean ok is false if it was not possible to recover the information.

        func Callers

        func Callers(skip int, pc []uintptr) int

        Callers fills the slice pc with the return program counters of function invocations on the calling goroutine's stack. The argument skip is the number of stack frames to skip before recording in pc, with 0 identifying the frame for Callers itself and 1 identifying the caller of Callers. It returns the number of entries written to pc.

        To translate these PCs into symbolic information such as function names and line numbers, use CallersFrames. CallersFrames accounts for inlined functions and adjusts the return program counters into call program counters. Iterating over the returned slice of PCs directly is discouraged, as is using FuncForPC on any of the returned PCs, since these cannot account for inlining or return program counter adjustment.

        func GC

        func GC()

        GC runs a garbage collection and blocks the caller until the garbage collection is complete. It may also block the entire program.

        func GOMAXPROCS

        func GOMAXPROCS(n int) int

        GOMAXPROCS sets the maximum number of CPUs that can be executing simultaneously and returns the previous setting. It defaults to the value of runtime.NumCPU. If n < 1, it does not change the current setting. This call will go away when the scheduler improves.

        func GOROOT

        func GOROOT() string

        GOROOT returns the root of the Go tree. It uses the GOROOT environment variable, if set at process start, or else the root used during the Go build.

        func Goexit

        func Goexit()

        Goexit terminates the goroutine that calls it. No other goroutine is affected. Goexit runs all deferred calls before terminating the goroutine. Because Goexit is not a panic, any recover calls in those deferred functions will return nil.

        Calling Goexit from the main goroutine terminates that goroutine without func main returning. Since func main has not returned, the program continues execution of other goroutines. If all other goroutines exit, the program crashes.

        func GoroutineProfile

        func GoroutineProfile(p []StackRecord) (n int, ok bool)

        GoroutineProfile returns n, the number of records in the active goroutine stack profile. If len(p) >= n, GoroutineProfile copies the profile into p and returns n, true. If len(p) < n, GoroutineProfile does not change p and returns n, false.

        Most clients should use the runtime/pprof package instead of calling GoroutineProfile directly.

        func Gosched

        func Gosched()

        Gosched yields the processor, allowing other goroutines to run. It does not suspend the current goroutine, so execution resumes automatically.

        func KeepAlive

        func KeepAlive(x any)

        KeepAlive marks its argument as currently reachable. This ensures that the object is not freed, and its finalizer is not run, before the point in the program where KeepAlive is called.

        A very simplified example showing where KeepAlive is required:

        type File struct { d int }
        d, err := syscall.Open("/file/path", syscall.O_RDONLY, 0)
        // ... do something if err != nil ...
        p := &File{d}
        runtime.SetFinalizer(p, func(p *File) { syscall.Close(p.d) })
        var buf [10]byte
        n, err := syscall.Read(p.d, buf[:])
        // Ensure p is not finalized until Read returns.
        runtime.KeepAlive(p)
        // No more uses of p after this point.
        

        Without the KeepAlive call, the finalizer could run at the start of syscall.Read, closing the file descriptor before syscall.Read makes the actual system call.

        Note: KeepAlive should only be used to prevent finalizers from running prematurely. In particular, when used with unsafe.Pointer, the rules for valid uses of unsafe.Pointer still apply.

        func LockOSThread

        func LockOSThread()

        LockOSThread wires the calling goroutine to its current operating system thread. The calling goroutine will always execute in that thread, and no other goroutine will execute in it, until the calling goroutine has made as many calls to UnlockOSThread as to LockOSThread. If the calling goroutine exits without unlocking the thread, the thread will be terminated.

        All init functions are run on the startup thread. Calling LockOSThread from an init function will cause the main function to be invoked on that thread.

        A goroutine should call LockOSThread before calling OS services or non-Go library functions that depend on per-thread state.

        func MemProfile

        func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool)

        MemProfile returns a profile of memory allocated and freed per allocation site.

        MemProfile returns n, the number of records in the current memory profile. If len(p) >= n, MemProfile copies the profile into p and returns n, true. If len(p) < n, MemProfile does not change p and returns n, false.

        If inuseZero is true, the profile includes allocation records where r.AllocBytes > 0 but r.AllocBytes == r.FreeBytes. These are sites where memory was allocated, but it has all been released back to the runtime.

        The returned profile may be up to two garbage collection cycles old. This is to avoid skewing the profile toward allocations; because allocations happen in real time but frees are delayed until the garbage collector performs sweeping, the profile only accounts for allocations that have had a chance to be freed by the garbage collector.

        Most clients should use the runtime/pprof package or the testing package's -test.memprofile flag instead of calling MemProfile directly.

        func MutexProfile

        func MutexProfile(p []BlockProfileRecord) (n int, ok bool)

        MutexProfile returns n, the number of records in the current mutex profile. If len(p) >= n, MutexProfile copies the profile into p and returns n, true. Otherwise, MutexProfile does not change p, and returns n, false.

        Most clients should use the runtime/pprof package instead of calling MutexProfile directly.

        func NumCPU

        func NumCPU() int

        NumCPU returns the number of logical CPUs usable by the current process.

        The set of available CPUs is checked by querying the operating system at process startup. Changes to operating system CPU allocation after process startup are not reflected.

        func NumCgoCall

        func NumCgoCall() int64

        NumCgoCall returns the number of cgo calls made by the current process.

        func NumGoroutine

        func NumGoroutine() int

        NumGoroutine returns the number of goroutines that currently exist.

        func ReadMemStats

        func ReadMemStats(m *MemStats)

        ReadMemStats populates m with memory allocator statistics.

        The returned memory allocator statistics are up to date as of the call to ReadMemStats. This is in contrast with a heap profile, which is a snapshot as of the most recently completed garbage collection cycle.

        func ReadTrace

        func ReadTrace() []byte

        ReadTrace returns the next chunk of binary tracing data, blocking until data is available. If tracing is turned off and all the data accumulated while it was on has been returned, ReadTrace returns nil. The caller must copy the returned data before calling ReadTrace again. ReadTrace must be called from one goroutine at a time.

        func SetBlockProfileRate

        func SetBlockProfileRate(rate int)

        SetBlockProfileRate controls the fraction of goroutine blocking events that are reported in the blocking profile. The profiler aims to sample an average of one blocking event per rate nanoseconds spent blocked.

        To include every blocking event in the profile, pass rate = 1. To turn off profiling entirely, pass rate <= 0.

        func SetCPUProfileRate

        func SetCPUProfileRate(hz int)

        SetCPUProfileRate sets the CPU profiling rate to hz samples per second. If hz <= 0, SetCPUProfileRate turns off profiling. If the profiler is on, the rate cannot be changed without first turning it off.

        Most clients should use the runtime/pprof package or the testing package's -test.cpuprofile flag instead of calling SetCPUProfileRate directly.

        func SetCgoTraceback

        func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer)

        SetCgoTraceback records three C functions to use to gather traceback information from C code and to convert that traceback information into symbolic information. These are used when printing stack traces for a program that uses cgo.

        The traceback and context functions may be called from a signal handler, and must therefore use only async-signal safe functions. The symbolizer function may be called while the program is crashing, and so must be cautious about using memory. None of the functions may call back into Go.

        The context function will be called with a single argument, a pointer to a struct:

        struct {
        	Context uintptr
        }
        

        In C syntax, this struct will be

        struct {
        	uintptr_t Context;
        };
        

        If the Context field is 0, the context function is being called to record the current traceback context. It should record in the Context field whatever information is needed about the current point of execution to later produce a stack trace, probably the stack pointer and PC. In this case the context function will be called from C code.

        If the Context field is not 0, then it is a value returned by a previous call to the context function. This case is called when the context is no longer needed; that is, when the Go code is returning to its C code caller. This permits the context function to release any associated resources.

        While it would be correct for the context function to record a complete a stack trace whenever it is called, and simply copy that out in the traceback function, in a typical program the context function will be called many times without ever recording a traceback for that context. Recording a complete stack trace in a call to the context function is likely to be inefficient.

        The traceback function will be called with a single argument, a pointer to a struct:

        struct {
        	Context    uintptr
        	SigContext uintptr
        	Buf        *uintptr
        	Max        uintptr
        }
        

        In C syntax, this struct will be

        struct {
        	uintptr_t  Context;
        	uintptr_t  SigContext;
        	uintptr_t* Buf;
        	uintptr_t  Max;
        };
        

        The Context field will be zero to gather a traceback from the current program execution point. In this case, the traceback function will be called from C code.

        Otherwise Context will be a value previously returned by a call to the context function. The traceback function should gather a stack trace from that saved point in the program execution. The traceback function may be called from an execution thread other than the one that recorded the context, but only when the context is known to be valid and unchanging. The traceback function may also be called deeper in the call stack on the same thread that recorded the context. The traceback function may be called multiple times with the same Context value; it will usually be appropriate to cache the result, if possible, the first time this is called for a specific context value.

        If the traceback function is called from a signal handler on a Unix system, SigContext will be the signal context argument passed to the signal handler (a C ucontext_t* cast to uintptr_t). This may be used to start tracing at the point where the signal occurred. If the traceback function is not called from a signal handler, SigContext will be zero.

        Buf is where the traceback information should be stored. It should be PC values, such that Buf[0] is the PC of the caller, Buf[1] is the PC of that function's caller, and so on. Max is the maximum number of entries to store. The function should store a zero to indicate the top of the stack, or that the caller is on a different stack, presumably a Go stack.

        Unlike runtime.Callers, the PC values returned should, when passed to the symbolizer function, return the file/line of the call instruction. No additional subtraction is required or appropriate.

        On all platforms, the traceback function is invoked when a call from Go to C to Go requests a stack trace. On linux/amd64, linux/ppc64le, linux/arm64, and freebsd/amd64, the traceback function is also invoked when a signal is received by a thread that is executing a cgo call. The traceback function should not make assumptions about when it is called, as future versions of Go may make additional calls.

        The symbolizer function will be called with a single argument, a pointer to a struct:

        struct {
        	PC      uintptr // program counter to fetch information for
        	File    *byte   // file name (NUL terminated)
        	Lineno  uintptr // line number
        	Func    *byte   // function name (NUL terminated)
        	Entry   uintptr // function entry point
        	More    uintptr // set non-zero if more info for this PC
        	Data    uintptr // unused by runtime, available for function
        }
        

        In C syntax, this struct will be

        struct {
        	uintptr_t PC;
        	char*     File;
        	uintptr_t Lineno;
        	char*     Func;
        	uintptr_t Entry;
        	uintptr_t More;
        	uintptr_t Data;
        };
        

        The PC field will be a value returned by a call to the traceback function.

        The first time the function is called for a particular traceback, all the fields except PC will be 0. The function should fill in the other fields if possible, setting them to 0/nil if the information is not available. The Data field may be used to store any useful information across calls. The More field should be set to non-zero if there is more information for this PC, zero otherwise. If More is set non-zero, the function will be called again with the same PC, and may return different information (this is intended for use with inlined functions). If More is zero, the function will be called with the next PC value in the traceback. When the traceback is complete, the function will be called once more with PC set to zero; this may be used to free any information. Each call will leave the fields of the struct set to the same values they had upon return, except for the PC field when the More field is zero. The function must not keep a copy of the struct pointer between calls.

        When calling SetCgoTraceback, the version argument is the version number of the structs that the functions expect to receive. Currently this must be zero.

        The symbolizer function may be nil, in which case the results of the traceback function will be displayed as numbers. If the traceback function is nil, the symbolizer function will never be called. The context function may be nil, in which case the traceback function will only be called with the context field set to zero. If the context function is nil, then calls from Go to C to Go will not show a traceback for the C portion of the call stack.

        SetCgoTraceback should be called only once, ideally from an init function.

        func SetFinalizer

        func SetFinalizer(obj any, finalizer any)

        SetFinalizer sets the finalizer associated with obj to the provided finalizer function. When the garbage collector finds an unreachable block with an associated finalizer, it clears the association and runs finalizer(obj) in a separate goroutine. This makes obj reachable again, but now without an associated finalizer. Assuming that SetFinalizer is not called again, the next time the garbage collector sees that obj is unreachable, it will free obj.

        SetFinalizer(obj, nil) clears any finalizer associated with obj.

        The argument obj must be a pointer to an object allocated by calling new, by taking the address of a composite literal, or by taking the address of a local variable. The argument finalizer must be a function that takes a single argument to which obj's type can be assigned, and can have arbitrary ignored return values. If either of these is not true, SetFinalizer may abort the program.

        Finalizers are run in dependency order: if A points at B, both have finalizers, and they are otherwise unreachable, only the finalizer for A runs; once A is freed, the finalizer for B can run. If a cyclic structure includes a block with a finalizer, that cycle is not guaranteed to be garbage collected and the finalizer is not guaranteed to run, because there is no ordering that respects the dependencies.

        The finalizer is scheduled to run at some arbitrary time after the program can no longer reach the object to which obj points. There is no guarantee that finalizers will run before a program exits, so typically they are useful only for releasing non-memory resources associated with an object during a long-running program. For example, an os.File object could use a finalizer to close the associated operating system file descriptor when a program discards an os.File without calling Close, but it would be a mistake to depend on a finalizer to flush an in-memory I/O buffer such as a bufio.Writer, because the buffer would not be flushed at program exit.

        It is not guaranteed that a finalizer will run if the size of *obj is zero bytes, because it may share same address with other zero-size objects in memory. See https://go.dev/ref/spec#Size_and_alignment_guarantees.

        It is not guaranteed that a finalizer will run for objects allocated in initializers for package-level variables. Such objects may be linker-allocated, not heap-allocated.

        Note that because finalizers may execute arbitrarily far into the future after an object is no longer referenced, the runtime is allowed to perform a space-saving optimization that batches objects together in a single allocation slot. The finalizer for an unreferenced object in such an allocation may never run if it always exists in the same batch as a referenced object. Typically, this batching only happens for tiny (on the order of 16 bytes or less) and pointer-free objects.

        A finalizer may run as soon as an object becomes unreachable. In order to use finalizers correctly, the program must ensure that the object is reachable until it is no longer required. Objects stored in global variables, or that can be found by tracing pointers from a global variable, are reachable. For other objects, pass the object to a call of the KeepAlive function to mark the last point in the function where the object must be reachable.

        For example, if p points to a struct, such as os.File, that contains a file descriptor d, and p has a finalizer that closes that file descriptor, and if the last use of p in a function is a call to syscall.Write(p.d, buf, size), then p may be unreachable as soon as the program enters syscall.Write. The finalizer may run at that moment, closing p.d, causing syscall.Write to fail because it is writing to a closed file descriptor (or, worse, to an entirely different file descriptor opened by a different goroutine). To avoid this problem, call KeepAlive(p) after the call to syscall.Write.

        A single goroutine runs all finalizers for a program, sequentially. If a finalizer must run for a long time, it should do so by starting a new goroutine.

        In the terminology of the Go memory model, a call SetFinalizer(x, f) “synchronizes before” the finalization call f(x). However, there is no guarantee that KeepAlive(x) or any other use of x “synchronizes before” f(x), so in general a finalizer should use a mutex or other synchronization mechanism if it needs to access mutable state in x. For example, consider a finalizer that inspects a mutable field in x that is modified from time to time in the main program before x becomes unreachable and the finalizer is invoked. The modifications in the main program and the inspection in the finalizer need to use appropriate synchronization, such as mutexes or atomic updates, to avoid read-write races.

        func SetMutexProfileFraction

        func SetMutexProfileFraction(rate int) int

        SetMutexProfileFraction controls the fraction of mutex contention events that are reported in the mutex profile. On average 1/rate events are reported. The previous rate is returned.

        To turn off profiling entirely, pass rate 0. To just read the current rate, pass rate < 0. (For n>1 the details of sampling may change.)

        func Stack

        func Stack(buf []byte, all bool) int

        Stack formats a stack trace of the calling goroutine into buf and returns the number of bytes written to buf. If all is true, Stack formats stack traces of all other goroutines into buf after the trace for the current goroutine.

        func StartTrace

        func StartTrace() error

        StartTrace enables tracing for the current process. While tracing, the data will be buffered and available via ReadTrace. StartTrace returns an error if tracing is already enabled. Most clients should use the runtime/trace package or the testing package's -test.trace flag instead of calling StartTrace directly.

        func StopTrace

        func StopTrace()

        StopTrace stops tracing, if it was previously enabled. StopTrace only returns after all the reads for the trace have completed.

        func ThreadCreateProfile

        func ThreadCreateProfile(p []StackRecord) (n int, ok bool)

        ThreadCreateProfile returns n, the number of records in the thread creation profile. If len(p) >= n, ThreadCreateProfile copies the profile into p and returns n, true. If len(p) < n, ThreadCreateProfile does not change p and returns n, false.

        Most clients should use the runtime/pprof package instead of calling ThreadCreateProfile directly.

        func UnlockOSThread

        func UnlockOSThread()

        UnlockOSThread undoes an earlier call to LockOSThread. If this drops the number of active LockOSThread calls on the calling goroutine to zero, it unwires the calling goroutine from its fixed operating system thread. If there are no active LockOSThread calls, this is a no-op.

        Before calling UnlockOSThread, the caller must ensure that the OS thread is suitable for running other goroutines. If the caller made any permanent changes to the state of the thread that would affect other goroutines, it should not call this function and thus leave the goroutine locked to the OS thread until the goroutine (and hence the thread) exits.

        func Version

        func Version() string

        Version returns the Go tree's version string. It is either the commit hash and date at the time of the build or, when possible, a release tag like "go1.3".

        type BlockProfileRecord

        BlockProfileRecord describes blocking events originated at a particular call sequence (stack trace).

        type BlockProfileRecord struct {
            Count  int64
            Cycles int64
            StackRecord
        }
        

        type Error

        The Error interface identifies a run time error.

        type Error interface {
            error
        
            // RuntimeError is a no-op function but
            // serves to distinguish types that are run time
            // errors from ordinary errors: a type is a
            // run time error if it has a RuntimeError method.
            RuntimeError()
        }

        type Frame

        Frame is the information returned by Frames for each call frame.

        type Frame struct {
            // PC is the program counter for the location in this frame.
            // For a frame that calls another frame, this will be the
            // program counter of a call instruction. Because of inlining,
            // multiple frames may have the same PC value, but different
            // symbolic information.
            PC uintptr
        
            // Func is the Func value of this call frame. This may be nil
            // for non-Go code or fully inlined functions.
            Func *Func
        
            // Function is the package path-qualified function name of
            // this call frame. If non-empty, this string uniquely
            // identifies a single function in the program.
            // This may be the empty string if not known.
            // If Func is not nil then Function == Func.Name().
            Function string
        
            // File and Line are the file name and line number of the
            // location in this frame. For non-leaf frames, this will be
            // the location of a call. These may be the empty string and
            // zero, respectively, if not known.
            File string
            Line int
        
            // Entry point program counter for the function; may be zero
            // if not known. If Func is not nil then Entry ==
            // Func.Entry().
            Entry uintptr
            // contains filtered or unexported fields
        }
        

        type Frames

        Frames may be used to get function/file/line information for a slice of PC values returned by Callers.

        type Frames struct {
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        c := func() {
            // Ask runtime.Callers for up to 10 PCs, including runtime.Callers itself.
            pc := make([]uintptr, 10)
            n := runtime.Callers(0, pc)
            if n == 0 {
                // No PCs available. This can happen if the first argument to
                // runtime.Callers is large.
                //
                // Return now to avoid processing the zero Frame that would
                // otherwise be returned by frames.Next below.
                return
            }
        
            pc = pc[:n] // pass only valid pcs to runtime.CallersFrames
            frames := runtime.CallersFrames(pc)
        
            // Loop to get frames.
            // A fixed number of PCs can expand to an indefinite number of Frames.
            for {
                frame, more := frames.Next()
        
                // Process this frame.
                //
                // To keep this example's output stable
                // even if there are changes in the testing package,
                // stop unwinding when we leave package runtime.
                if !strings.Contains(frame.File, "runtime/") {
                    break
                }
                fmt.Printf("- more:%v | %s\n", more, frame.Function)
        
                // Check whether there are more frames to process after this one.
                if !more {
                    break
                }
            }
        }
        
        b := func() { c() }
        a := func() { b() }
        
        a()
        

        Output:

        - more:true | runtime.Callers
        - more:true | runtime_test.ExampleFrames.func1
        - more:true | runtime_test.ExampleFrames.func2
        - more:true | runtime_test.ExampleFrames.func3
        - more:true | runtime_test.ExampleFrames
        

        func CallersFrames

        func CallersFrames(callers []uintptr) *Frames

        CallersFrames takes a slice of PC values returned by Callers and prepares to return function/file/line information. Do not change the slice until you are done with the Frames.

        func (*Frames) Next

        func (ci *Frames) Next() (frame Frame, more bool)

        Next returns a Frame representing the next call frame in the slice of PC values. If it has already returned all call frames, Next returns a zero Frame.

        The more result indicates whether the next call to Next will return a valid Frame. It does not necessarily indicate whether this call returned one.

        See the Frames example for idiomatic usage.

        type Func

        A Func represents a Go function in the running binary.

        type Func struct {
            // contains filtered or unexported fields
        }
        

        func FuncForPC

        func FuncForPC(pc uintptr) *Func

        FuncForPC returns a *Func describing the function that contains the given program counter address, or else nil.

        If pc represents multiple functions because of inlining, it returns the *Func describing the innermost function, but with an entry of the outermost function.

        func (*Func) Entry

        func (f *Func) Entry() uintptr

        Entry returns the entry address of the function.

        func (*Func) FileLine

        func (f *Func) FileLine(pc uintptr) (file string, line int)

        FileLine returns the file name and line number of the source code corresponding to the program counter pc. The result will not be accurate if pc is not a program counter within f.

        func (*Func) Name

        func (f *Func) Name() string

        Name returns the name of the function.

        type MemProfileRecord

        A MemProfileRecord describes the live objects allocated by a particular call sequence (stack trace).

        type MemProfileRecord struct {
            AllocBytes, FreeBytes     int64       // number of bytes allocated, freed
            AllocObjects, FreeObjects int64       // number of objects allocated, freed
            Stack0                    [32]uintptr // stack trace for this record; ends at first 0 entry
        }
        

        func (*MemProfileRecord) InUseBytes

        func (r *MemProfileRecord) InUseBytes() int64

        InUseBytes returns the number of bytes in use (AllocBytes - FreeBytes).

        func (*MemProfileRecord) InUseObjects

        func (r *MemProfileRecord) InUseObjects() int64

        InUseObjects returns the number of objects in use (AllocObjects - FreeObjects).

        func (*MemProfileRecord) Stack

        func (r *MemProfileRecord) Stack() []uintptr

        Stack returns the stack trace associated with the record, a prefix of r.Stack0.

        type MemStats

        A MemStats records statistics about the memory allocator.

        type MemStats struct {
        
            // Alloc is bytes of allocated heap objects.
            //
            // This is the same as HeapAlloc (see below).
            Alloc uint64
        
            // TotalAlloc is cumulative bytes allocated for heap objects.
            //
            // TotalAlloc increases as heap objects are allocated, but
            // unlike Alloc and HeapAlloc, it does not decrease when
            // objects are freed.
            TotalAlloc uint64
        
            // Sys is the total bytes of memory obtained from the OS.
            //
            // Sys is the sum of the XSys fields below. Sys measures the
            // virtual address space reserved by the Go runtime for the
            // heap, stacks, and other internal data structures. It's
            // likely that not all of the virtual address space is backed
            // by physical memory at any given moment, though in general
            // it all was at some point.
            Sys uint64
        
            // Lookups is the number of pointer lookups performed by the
            // runtime.
            //
            // This is primarily useful for debugging runtime internals.
            Lookups uint64
        
            // Mallocs is the cumulative count of heap objects allocated.
            // The number of live objects is Mallocs - Frees.
            Mallocs uint64
        
            // Frees is the cumulative count of heap objects freed.
            Frees uint64
        
            // HeapAlloc is bytes of allocated heap objects.
            //
            // "Allocated" heap objects include all reachable objects, as
            // well as unreachable objects that the garbage collector has
            // not yet freed. Specifically, HeapAlloc increases as heap
            // objects are allocated and decreases as the heap is swept
            // and unreachable objects are freed. Sweeping occurs
            // incrementally between GC cycles, so these two processes
            // occur simultaneously, and as a result HeapAlloc tends to
            // change smoothly (in contrast with the sawtooth that is
            // typical of stop-the-world garbage collectors).
            HeapAlloc uint64
        
            // HeapSys is bytes of heap memory obtained from the OS.
            //
            // HeapSys measures the amount of virtual address space
            // reserved for the heap. This includes virtual address space
            // that has been reserved but not yet used, which consumes no
            // physical memory, but tends to be small, as well as virtual
            // address space for which the physical memory has been
            // returned to the OS after it became unused (see HeapReleased
            // for a measure of the latter).
            //
            // HeapSys estimates the largest size the heap has had.
            HeapSys uint64
        
            // HeapIdle is bytes in idle (unused) spans.
            //
            // Idle spans have no objects in them. These spans could be
            // (and may already have been) returned to the OS, or they can
            // be reused for heap allocations, or they can be reused as
            // stack memory.
            //
            // HeapIdle minus HeapReleased estimates the amount of memory
            // that could be returned to the OS, but is being retained by
            // the runtime so it can grow the heap without requesting more
            // memory from the OS. If this difference is significantly
            // larger than the heap size, it indicates there was a recent
            // transient spike in live heap size.
            HeapIdle uint64
        
            // HeapInuse is bytes in in-use spans.
            //
            // In-use spans have at least one object in them. These spans
            // can only be used for other objects of roughly the same
            // size.
            //
            // HeapInuse minus HeapAlloc estimates the amount of memory
            // that has been dedicated to particular size classes, but is
            // not currently being used. This is an upper bound on
            // fragmentation, but in general this memory can be reused
            // efficiently.
            HeapInuse uint64
        
            // HeapReleased is bytes of physical memory returned to the OS.
            //
            // This counts heap memory from idle spans that was returned
            // to the OS and has not yet been reacquired for the heap.
            HeapReleased uint64
        
            // HeapObjects is the number of allocated heap objects.
            //
            // Like HeapAlloc, this increases as objects are allocated and
            // decreases as the heap is swept and unreachable objects are
            // freed.
            HeapObjects uint64
        
            // StackInuse is bytes in stack spans.
            //
            // In-use stack spans have at least one stack in them. These
            // spans can only be used for other stacks of the same size.
            //
            // There is no StackIdle because unused stack spans are
            // returned to the heap (and hence counted toward HeapIdle).
            StackInuse uint64
        
            // StackSys is bytes of stack memory obtained from the OS.
            //
            // StackSys is StackInuse, plus any memory obtained directly
            // from the OS for OS thread stacks.
            //
            // In non-cgo programs this metric is currently equal to StackInuse
            // (but this should not be relied upon, and the value may change in
            // the future).
            //
            // In cgo programs this metric includes OS thread stacks allocated
            // directly from the OS. Currently, this only accounts for one stack in
            // c-shared and c-archive build modes and other sources of stacks from
            // the OS (notably, any allocated by C code) are not currently measured.
            // Note this too may change in the future.
            StackSys uint64
        
            // MSpanInuse is bytes of allocated mspan structures.
            MSpanInuse uint64
        
            // MSpanSys is bytes of memory obtained from the OS for mspan
            // structures.
            MSpanSys uint64
        
            // MCacheInuse is bytes of allocated mcache structures.
            MCacheInuse uint64
        
            // MCacheSys is bytes of memory obtained from the OS for
            // mcache structures.
            MCacheSys uint64
        
            // BuckHashSys is bytes of memory in profiling bucket hash tables.
            BuckHashSys uint64
        
            // GCSys is bytes of memory in garbage collection metadata.
            GCSys uint64
        
            // OtherSys is bytes of memory in miscellaneous off-heap
            // runtime allocations.
            OtherSys uint64
        
            // NextGC is the target heap size of the next GC cycle.
            //
            // The garbage collector's goal is to keep HeapAlloc ≤ NextGC.
            // At the end of each GC cycle, the target for the next cycle
            // is computed based on the amount of reachable data and the
            // value of GOGC.
            NextGC uint64
        
            // LastGC is the time the last garbage collection finished, as
            // nanoseconds since 1970 (the UNIX epoch).
            LastGC uint64
        
            // PauseTotalNs is the cumulative nanoseconds in GC
            // stop-the-world pauses since the program started.
            //
            // During a stop-the-world pause, all goroutines are paused
            // and only the garbage collector can run.
            PauseTotalNs uint64
        
            // PauseNs is a circular buffer of recent GC stop-the-world
            // pause times in nanoseconds.
            //
            // The most recent pause is at PauseNs[(NumGC+255)%256]. In
            // general, PauseNs[N%256] records the time paused in the most
            // recent N%256th GC cycle. There may be multiple pauses per
            // GC cycle; this is the sum of all pauses during a cycle.
            PauseNs [256]uint64
        
            // PauseEnd is a circular buffer of recent GC pause end times,
            // as nanoseconds since 1970 (the UNIX epoch).
            //
            // This buffer is filled the same way as PauseNs. There may be
            // multiple pauses per GC cycle; this records the end of the
            // last pause in a cycle.
            PauseEnd [256]uint64
        
            // NumGC is the number of completed GC cycles.
            NumGC uint32
        
            // NumForcedGC is the number of GC cycles that were forced by
            // the application calling the GC function.
            NumForcedGC uint32
        
            // GCCPUFraction is the fraction of this program's available
            // CPU time used by the GC since the program started.
            //
            // GCCPUFraction is expressed as a number between 0 and 1,
            // where 0 means GC has consumed none of this program's CPU. A
            // program's available CPU time is defined as the integral of
            // GOMAXPROCS since the program started. That is, if
            // GOMAXPROCS is 2 and a program has been running for 10
            // seconds, its "available CPU" is 20 seconds. GCCPUFraction
            // does not include CPU time used for write barrier activity.
            //
            // This is the same as the fraction of CPU reported by
            // GODEBUG=gctrace=1.
            GCCPUFraction float64
        
            // EnableGC indicates that GC is enabled. It is always true,
            // even if GOGC=off.
            EnableGC bool
        
            // DebugGC is currently unused.
            DebugGC bool
        
            // BySize reports per-size class allocation statistics.
            //
            // BySize[N] gives statistics for allocations of size S where
            // BySize[N-1].Size < S ≤ BySize[N].Size.
            //
            // This does not report allocations larger than BySize[60].Size.
            BySize [61]struct {
                // Size is the maximum byte size of an object in this
                // size class.
                Size uint32
        
                // Mallocs is the cumulative count of heap objects
                // allocated in this size class. The cumulative bytes
                // of allocation is Size*Mallocs. The number of live
                // objects in this size class is Mallocs - Frees.
                Mallocs uint64
        
                // Frees is the cumulative count of heap objects freed
                // in this size class.
                Frees uint64
            }
        }
        

        type PanicNilError

        A PanicNilError happens when code calls panic(nil).

        Before Go 1.21, programs that called panic(nil) observed recover returning nil. Starting in Go 1.21, programs that call panic(nil) observe recover returning a *PanicNilError. Programs can change back to the old behavior by setting GODEBUG=panicnil=1.

        type PanicNilError struct {
            // contains filtered or unexported fields
        }
        

        func (*PanicNilError) Error

        func (*PanicNilError) Error() string

        func (*PanicNilError) RuntimeError

        func (*PanicNilError) RuntimeError()

        type Pinner

        A Pinner is a set of Go objects each pinned to a fixed location in memory. The Pinner.Pin method pins one object, while Pinner.Unpin unpins all pinned objects. See their comments for more information.

        type Pinner struct {
            // contains filtered or unexported fields
        }
        

        func (*Pinner) Pin

        func (p *Pinner) Pin(pointer any)

        Pin pins a Go object, preventing it from being moved or freed by the garbage collector until the Pinner.Unpin method has been called.

        A pointer to a pinned object can be directly stored in C memory or can be contained in Go memory passed to C functions. If the pinned object itself contains pointers to Go objects, these objects must be pinned separately if they are going to be accessed from C code.

        The argument must be a pointer of any type or an unsafe.Pointer. It's safe to call Pin on non-Go pointers, in which case Pin will do nothing.

        func (*Pinner) Unpin

        func (p *Pinner) Unpin()

        Unpin unpins all pinned objects of the Pinner.

        type StackRecord

        A StackRecord describes a single execution stack.

        type StackRecord struct {
            Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry
        }
        

        func (*StackRecord) Stack

        func (r *StackRecord) Stack() []uintptr

        Stack returns the stack trace associated with the record, a prefix of r.Stack0.

        type TypeAssertionError

        A TypeAssertionError explains a failed type assertion.

        type TypeAssertionError struct {
            // contains filtered or unexported fields
        }
        

        func (*TypeAssertionError) Error

        func (e *TypeAssertionError) Error() string

        func (*TypeAssertionError) RuntimeError

        func (*TypeAssertionError) RuntimeError()

        Subdirectories

        Name Synopsis
        ..
        asan
        cgo Package cgo contains runtime support for code generated by the cgo tool.
        coverage
        debug Package debug contains facilities for programs to debug themselves while they are running.
        metrics Package metrics provides a stable interface to access implementation-defined metrics exported by the Go runtime.
        msan
        pprof Package pprof writes runtime profiling data in the format expected by the pprof visualization tool.
        race Package race implements data race detection logic.
        trace Package trace contains facilities for programs to generate traces for the Go execution tracer.
        asan - Go Documentation Server
        ...

        Command asan

        cgo - Go Documentation Server
        ...

        Package cgo

        import "runtime/cgo"
        Overview
        Index

        Overview ▾

        Package cgo contains runtime support for code generated by the cgo tool. See the documentation for the cgo command for details on using cgo.

        type Handle

        Handle provides a way to pass values that contain Go pointers (pointers to memory allocated by Go) between Go and C without breaking the cgo pointer passing rules. A Handle is an integer value that can represent any Go value. A Handle can be passed through C and back to Go, and Go code can use the Handle to retrieve the original Go value.

        The underlying type of Handle is guaranteed to fit in an integer type that is large enough to hold the bit pattern of any pointer. The zero value of a Handle is not valid, and thus is safe to use as a sentinel in C APIs.

        For instance, on the Go side:

        package main
        
        /*
        #include <stdint.h> // for uintptr_t
        
        extern void MyGoPrint(uintptr_t handle);
        void myprint(uintptr_t handle);
        */
        import "C"
        import "runtime/cgo"
        
        //export MyGoPrint
        func MyGoPrint(handle C.uintptr_t) {
        	h := cgo.Handle(handle)
        	val := h.Value().(string)
        	println(val)
        	h.Delete()
        }
        
        func main() {
        	val := "hello Go"
        	C.myprint(C.uintptr_t(cgo.NewHandle(val)))
        	// Output: hello Go
        }
        

        and on the C side:

        #include <stdint.h> // for uintptr_t
        
        // A Go function
        extern void MyGoPrint(uintptr_t handle);
        
        // A C function
        void myprint(uintptr_t handle) {
            MyGoPrint(handle);
        }
        

        Some C functions accept a void* argument that points to an arbitrary data value supplied by the caller. It is not safe to coerce a cgo.Handle (an integer) to a Go unsafe.Pointer, but instead we can pass the address of the cgo.Handle to the void* parameter, as in this variant of the previous example:

        package main
        
        /*
        extern void MyGoPrint(void *context);
        static inline void myprint(void *context) {
            MyGoPrint(context);
        }
        */
        import "C"
        import (
        	"runtime/cgo"
        	"unsafe"
        )
        
        //export MyGoPrint
        func MyGoPrint(context unsafe.Pointer) {
        	h := *(*cgo.Handle)(context)
        	val := h.Value().(string)
        	println(val)
        	h.Delete()
        }
        
        func main() {
        	val := "hello Go"
        	h := cgo.NewHandle(val)
        	C.myprint(unsafe.Pointer(&h))
        	// Output: hello Go
        }
        
        type Handle uintptr

        func NewHandle

        func NewHandle(v any) Handle

        NewHandle returns a handle for a given value.

        The handle is valid until the program calls Delete on it. The handle uses resources, and this package assumes that C code may hold on to the handle, so a program must explicitly call Delete when the handle is no longer needed.

        The intended use is to pass the returned handle to C code, which passes it back to Go, which calls Value.

        func (Handle) Delete

        func (h Handle) Delete()

        Delete invalidates a handle. This method should only be called once the program no longer needs to pass the handle to C and the C code no longer has a copy of the handle value.

        The method panics if the handle is invalid.

        func (Handle) Value

        func (h Handle) Value() any

        Value returns the associated Go value for a valid handle.

        The method panics if the handle is invalid.

        type Incomplete

        Incomplete is used specifically for the semantics of incomplete C types.

        type Incomplete struct {
            // contains filtered or unexported fields
        }
        
        coverage - Go Documentation Server
        ...

        Package coverage

        import "runtime/coverage"
        Overview
        Index

        Overview ▾

        func ClearCounters

        func ClearCounters() error

        ClearCounters clears/resets all coverage counter variables in the currently running program. It returns an error if the program in question was not built with the "-cover" flag. Clearing of coverage counters is also not supported for programs not using atomic counter mode (see more detailed comments below for the rationale here).

        func WriteCounters

        func WriteCounters(w io.Writer) error

        WriteCounters writes coverage counter-data content for the currently running program to the writer 'w'. An error will be returned if the operation can't be completed successfully (for example, if the currently running program was not built with "-cover", or if a write fails). The counter data written will be a snapshot taken at the point of the invocation.

        func WriteCountersDir

        func WriteCountersDir(dir string) error

        WriteCountersDir writes a coverage counter-data file for the currently running program to the directory specified in 'dir'. An error will be returned if the operation can't be completed successfully (for example, if the currently running program was not built with "-cover", or if the directory does not exist). The counter data written will be a snapshot taken at the point of the call.

        func WriteMeta

        func WriteMeta(w io.Writer) error

        WriteMeta writes the meta-data content (the payload that would normally be emitted to a meta-data file) for the currently running program to the writer 'w'. An error will be returned if the operation can't be completed successfully (for example, if the currently running program was not built with "-cover", or if a write fails).

        func WriteMetaDir

        func WriteMetaDir(dir string) error

        WriteMetaDir writes a coverage meta-data file for the currently running program to the directory specified in 'dir'. An error will be returned if the operation can't be completed successfully (for example, if the currently running program was not built with "-cover", or if the directory does not exist).

        debug - Go Documentation Server
        ...

        Package debug

        import "runtime/debug"
        Overview
        Index

        Overview ▾

        Package debug contains facilities for programs to debug themselves while they are running.

        func FreeOSMemory

        func FreeOSMemory()

        FreeOSMemory forces a garbage collection followed by an attempt to return as much memory to the operating system as possible. (Even if this is not called, the runtime gradually returns memory to the operating system in a background task.)

        func PrintStack

        func PrintStack()

        PrintStack prints to standard error the stack trace returned by runtime.Stack.

        func ReadGCStats

        func ReadGCStats(stats *GCStats)

        ReadGCStats reads statistics about garbage collection into stats. The number of entries in the pause history is system-dependent; stats.Pause slice will be reused if large enough, reallocated otherwise. ReadGCStats may use the full capacity of the stats.Pause slice. If stats.PauseQuantiles is non-empty, ReadGCStats fills it with quantiles summarizing the distribution of pause time. For example, if len(stats.PauseQuantiles) is 5, it will be filled with the minimum, 25%, 50%, 75%, and maximum pause times.

        func SetGCPercent

        func SetGCPercent(percent int) int

        SetGCPercent sets the garbage collection target percentage: a collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. SetGCPercent returns the previous setting. The initial setting is the value of the GOGC environment variable at startup, or 100 if the variable is not set. This setting may be effectively reduced in order to maintain a memory limit. A negative percentage effectively disables garbage collection, unless the memory limit is reached. See SetMemoryLimit for more details.

        func SetMaxStack

        func SetMaxStack(bytes int) int

        SetMaxStack sets the maximum amount of memory that can be used by a single goroutine stack. If any goroutine exceeds this limit while growing its stack, the program crashes. SetMaxStack returns the previous setting. The initial setting is 1 GB on 64-bit systems, 250 MB on 32-bit systems. There may be a system-imposed maximum stack limit regardless of the value provided to SetMaxStack.

        SetMaxStack is useful mainly for limiting the damage done by goroutines that enter an infinite recursion. It only limits future stack growth.

        func SetMaxThreads

        func SetMaxThreads(threads int) int

        SetMaxThreads sets the maximum number of operating system threads that the Go program can use. If it attempts to use more than this many, the program crashes. SetMaxThreads returns the previous setting. The initial setting is 10,000 threads.

        The limit controls the number of operating system threads, not the number of goroutines. A Go program creates a new thread only when a goroutine is ready to run but all the existing threads are blocked in system calls, cgo calls, or are locked to other goroutines due to use of runtime.LockOSThread.

        SetMaxThreads is useful mainly for limiting the damage done by programs that create an unbounded number of threads. The idea is to take down the program before it takes down the operating system.

        func SetMemoryLimit

        func SetMemoryLimit(limit int64) int64

        SetMemoryLimit provides the runtime with a soft memory limit.

        The runtime undertakes several processes to try to respect this memory limit, including adjustments to the frequency of garbage collections and returning memory to the underlying system more aggressively. This limit will be respected even if GOGC=off (or, if SetGCPercent(-1) is executed).

        The input limit is provided as bytes, and includes all memory mapped, managed, and not released by the Go runtime. Notably, it does not account for space used by the Go binary and memory external to Go, such as memory managed by the underlying system on behalf of the process, or memory managed by non-Go code inside the same process. Examples of excluded memory sources include: OS kernel memory held on behalf of the process, memory allocated by C code, and memory mapped by syscall.Mmap (because it is not managed by the Go runtime).

        More specifically, the following expression accurately reflects the value the runtime attempts to maintain as the limit:

        runtime.MemStats.Sys - runtime.MemStats.HeapReleased
        

        or in terms of the runtime/metrics package:

        /memory/classes/total:bytes - /memory/classes/heap/released:bytes
        

        A zero limit or a limit that's lower than the amount of memory used by the Go runtime may cause the garbage collector to run nearly continuously. However, the application may still make progress.

        The memory limit is always respected by the Go runtime, so to effectively disable this behavior, set the limit very high. math.MaxInt64 is the canonical value for disabling the limit, but values much greater than the available memory on the underlying system work just as well.

        See https://go.dev/doc/gc-guide for a detailed guide explaining the soft memory limit in more detail, as well as a variety of common use-cases and scenarios.

        The initial setting is math.MaxInt64 unless the GOMEMLIMIT environment variable is set, in which case it provides the initial setting. GOMEMLIMIT is a numeric value in bytes with an optional unit suffix. The supported suffixes include B, KiB, MiB, GiB, and TiB. These suffixes represent quantities of bytes as defined by the IEC 80000-13 standard. That is, they are based on powers of two: KiB means 2^10 bytes, MiB means 2^20 bytes, and so on.

        SetMemoryLimit returns the previously set memory limit. A negative input does not adjust the limit, and allows for retrieval of the currently set memory limit.

        func SetPanicOnFault

        func SetPanicOnFault(enabled bool) bool

        SetPanicOnFault controls the runtime's behavior when a program faults at an unexpected (non-nil) address. Such faults are typically caused by bugs such as runtime memory corruption, so the default response is to crash the program. Programs working with memory-mapped files or unsafe manipulation of memory may cause faults at non-nil addresses in less dramatic situations; SetPanicOnFault allows such programs to request that the runtime trigger only a panic, not a crash. The runtime.Error that the runtime panics with may have an additional method:

        Addr() uintptr
        

        If that method exists, it returns the memory address which triggered the fault. The results of Addr are best-effort and the veracity of the result may depend on the platform. SetPanicOnFault applies only to the current goroutine. It returns the previous setting.

        func SetTraceback

        func SetTraceback(level string)

        SetTraceback sets the amount of detail printed by the runtime in the traceback it prints before exiting due to an unrecovered panic or an internal runtime error. The level argument takes the same values as the GOTRACEBACK environment variable. For example, SetTraceback("all") ensure that the program prints all goroutines when it crashes. See the package runtime documentation for details. If SetTraceback is called with a level lower than that of the environment variable, the call is ignored.

        func Stack

        func Stack() []byte

        Stack returns a formatted stack trace of the goroutine that calls it. It calls runtime.Stack with a large enough buffer to capture the entire trace.

        func WriteHeapDump

        func WriteHeapDump(fd uintptr)

        WriteHeapDump writes a description of the heap and the objects in it to the given file descriptor.

        WriteHeapDump suspends the execution of all goroutines until the heap dump is completely written. Thus, the file descriptor must not be connected to a pipe or socket whose other end is in the same Go process; instead, use a temporary file or network socket.

        The heap dump format is defined at https://golang.org/s/go15heapdump.

        type BuildInfo

        BuildInfo represents the build information read from a Go binary.

        type BuildInfo struct {
            // GoVersion is the version of the Go toolchain that built the binary
            // (for example, "go1.19.2").
            GoVersion string
        
            // Path is the package path of the main package for the binary
            // (for example, "golang.org/x/tools/cmd/stringer").
            Path string
        
            // Main describes the module that contains the main package for the binary.
            Main Module
        
            // Deps describes all the dependency modules, both direct and indirect,
            // that contributed packages to the build of this binary.
            Deps []*Module
        
            // Settings describes the build settings used to build the binary.
            Settings []BuildSetting
        }
        

        func ParseBuildInfo

        func ParseBuildInfo(data string) (bi *BuildInfo, err error)

        func ReadBuildInfo

        func ReadBuildInfo() (info *BuildInfo, ok bool)

        ReadBuildInfo returns the build information embedded in the running binary. The information is available only in binaries built with module support.

        func (*BuildInfo) String

        func (bi *BuildInfo) String() string

        type BuildSetting

        A BuildSetting is a key-value pair describing one setting that influenced a build.

        Defined keys include:

        • -buildmode: the buildmode flag used (typically "exe")
        • -compiler: the compiler toolchain flag used (typically "gc")
        • CGO_ENABLED: the effective CGO_ENABLED environment variable
        • CGO_CFLAGS: the effective CGO_CFLAGS environment variable
        • CGO_CPPFLAGS: the effective CGO_CPPFLAGS environment variable
        • CGO_CXXFLAGS: the effective CGO_CXXFLAGS environment variable
        • CGO_LDFLAGS: the effective CGO_LDFLAGS environment variable
        • GOARCH: the architecture target
        • GOAMD64/GOARM/GO386/etc: the architecture feature level for GOARCH
        • GOOS: the operating system target
        • vcs: the version control system for the source tree where the build ran
        • vcs.revision: the revision identifier for the current commit or checkout
        • vcs.time: the modification time associated with vcs.revision, in RFC3339 format
        • vcs.modified: true or false indicating whether the source tree had local modifications
        type BuildSetting struct {
            // Key and Value describe the build setting.
            // Key must not contain an equals sign, space, tab, or newline.
            // Value must not contain newlines ('\n').
            Key, Value string
        }
        

        type GCStats

        GCStats collect information about recent garbage collections.

        type GCStats struct {
            LastGC         time.Time       // time of last collection
            NumGC          int64           // number of garbage collections
            PauseTotal     time.Duration   // total pause for all collections
            Pause          []time.Duration // pause history, most recent first
            PauseEnd       []time.Time     // pause end times history, most recent first
            PauseQuantiles []time.Duration
        }
        

        type Module

        A Module describes a single module included in a build.

        type Module struct {
            Path    string  // module path
            Version string  // module version
            Sum     string  // checksum
            Replace *Module // replaced by this module
        }
        
        metrics - Go Documentation Server
        ...

        Package metrics

        import "runtime/metrics"
        Overview
        Index
        Examples

        Overview ▾

        Package metrics provides a stable interface to access implementation-defined metrics exported by the Go runtime. This package is similar to existing functions like runtime.ReadMemStats and runtime/debug.ReadGCStats, but significantly more general.

        The set of metrics defined by this package may evolve as the runtime itself evolves, and also enables variation across Go implementations, whose relevant metric sets may not intersect.

        Interface

        Metrics are designated by a string key, rather than, for example, a field name in a struct. The full list of supported metrics is always available in the slice of Descriptions returned by All. Each Description also includes useful information about the metric.

        Thus, users of this API are encouraged to sample supported metrics defined by the slice returned by All to remain compatible across Go versions. Of course, situations arise where reading specific metrics is critical. For these cases, users are encouraged to use build tags, and although metrics may be deprecated and removed, users should consider this to be an exceptional and rare event, coinciding with a very large change in a particular Go implementation.

        Each metric key also has a "kind" (see ValueKind) that describes the format of the metric's value. In the interest of not breaking users of this package, the "kind" for a given metric is guaranteed not to change. If it must change, then a new metric will be introduced with a new key and a new "kind."

        Metric key format

        As mentioned earlier, metric keys are strings. Their format is simple and well-defined, designed to be both human and machine readable. It is split into two components, separated by a colon: a rooted path and a unit. The choice to include the unit in the key is motivated by compatibility: if a metric's unit changes, its semantics likely did also, and a new key should be introduced.

        For more details on the precise definition of the metric key's path and unit formats, see the documentation of the Name field of the Description struct.

        A note about floats

        This package supports metrics whose values have a floating-point representation. In order to improve ease-of-use, this package promises to never produce the following classes of floating-point values: NaN, infinity.

        Supported metrics

        Below is the full list of supported metrics, ordered lexicographically.

        /cgo/go-to-c-calls:calls
        	Count of calls made from Go to C by the current process.
        
        /cpu/classes/gc/mark/assist:cpu-seconds
        	Estimated total CPU time goroutines spent performing GC
        	tasks to assist the GC and prevent it from falling behind the
        	application. This metric is an overestimate, and not directly
        	comparable to system CPU time measurements. Compare only with
        	other /cpu/classes metrics.
        
        /cpu/classes/gc/mark/dedicated:cpu-seconds
        	Estimated total CPU time spent performing GC tasks on processors
        	(as defined by GOMAXPROCS) dedicated to those tasks. This metric
        	is an overestimate, and not directly comparable to system CPU
        	time measurements. Compare only with other /cpu/classes metrics.
        
        /cpu/classes/gc/mark/idle:cpu-seconds
        	Estimated total CPU time spent performing GC tasks on spare CPU
        	resources that the Go scheduler could not otherwise find a use
        	for. This should be subtracted from the total GC CPU time to
        	obtain a measure of compulsory GC CPU time. This metric is an
        	overestimate, and not directly comparable to system CPU time
        	measurements. Compare only with other /cpu/classes metrics.
        
        /cpu/classes/gc/pause:cpu-seconds
        	Estimated total CPU time spent with the application paused by
        	the GC. Even if only one thread is running during the pause,
        	this is computed as GOMAXPROCS times the pause latency because
        	nothing else can be executing. This is the exact sum of samples
        	in /sched/pauses/total/gc:seconds if each sample is multiplied
        	by GOMAXPROCS at the time it is taken. This metric is an
        	overestimate, and not directly comparable to system CPU time
        	measurements. Compare only with other /cpu/classes metrics.
        
        /cpu/classes/gc/total:cpu-seconds
        	Estimated total CPU time spent performing GC tasks. This metric
        	is an overestimate, and not directly comparable to system CPU
        	time measurements. Compare only with other /cpu/classes metrics.
        	Sum of all metrics in /cpu/classes/gc.
        
        /cpu/classes/idle:cpu-seconds
        	Estimated total available CPU time not spent executing
        	any Go or Go runtime code. In other words, the part of
        	/cpu/classes/total:cpu-seconds that was unused. This metric is
        	an overestimate, and not directly comparable to system CPU time
        	measurements. Compare only with other /cpu/classes metrics.
        
        /cpu/classes/scavenge/assist:cpu-seconds
        	Estimated total CPU time spent returning unused memory to the
        	underlying platform in response eagerly in response to memory
        	pressure. This metric is an overestimate, and not directly
        	comparable to system CPU time measurements. Compare only with
        	other /cpu/classes metrics.
        
        /cpu/classes/scavenge/background:cpu-seconds
        	Estimated total CPU time spent performing background tasks to
        	return unused memory to the underlying platform. This metric is
        	an overestimate, and not directly comparable to system CPU time
        	measurements. Compare only with other /cpu/classes metrics.
        
        /cpu/classes/scavenge/total:cpu-seconds
        	Estimated total CPU time spent performing tasks that return
        	unused memory to the underlying platform. This metric is an
        	overestimate, and not directly comparable to system CPU time
        	measurements. Compare only with other /cpu/classes metrics.
        	Sum of all metrics in /cpu/classes/scavenge.
        
        /cpu/classes/total:cpu-seconds
        	Estimated total available CPU time for user Go code or the Go
        	runtime, as defined by GOMAXPROCS. In other words, GOMAXPROCS
        	integrated over the wall-clock duration this process has been
        	executing for. This metric is an overestimate, and not directly
        	comparable to system CPU time measurements. Compare only with
        	other /cpu/classes metrics. Sum of all metrics in /cpu/classes.
        
        /cpu/classes/user:cpu-seconds
        	Estimated total CPU time spent running user Go code. This may
        	also include some small amount of time spent in the Go runtime.
        	This metric is an overestimate, and not directly comparable
        	to system CPU time measurements. Compare only with other
        	/cpu/classes metrics.
        
        /gc/cycles/automatic:gc-cycles
        	Count of completed GC cycles generated by the Go runtime.
        
        /gc/cycles/forced:gc-cycles
        	Count of completed GC cycles forced by the application.
        
        /gc/cycles/total:gc-cycles
        	Count of all completed GC cycles.
        
        /gc/gogc:percent
        	Heap size target percentage configured by the user, otherwise
        	100. This value is set by the GOGC environment variable, and the
        	runtime/debug.SetGCPercent function.
        
        /gc/gomemlimit:bytes
        	Go runtime memory limit configured by the user, otherwise
        	math.MaxInt64. This value is set by the GOMEMLIMIT environment
        	variable, and the runtime/debug.SetMemoryLimit function.
        
        /gc/heap/allocs-by-size:bytes
        	Distribution of heap allocations by approximate size.
        	Bucket counts increase monotonically. Note that this does not
        	include tiny objects as defined by /gc/heap/tiny/allocs:objects,
        	only tiny blocks.
        
        /gc/heap/allocs:bytes
        	Cumulative sum of memory allocated to the heap by the
        	application.
        
        /gc/heap/allocs:objects
        	Cumulative count of heap allocations triggered by the
        	application. Note that this does not include tiny objects as
        	defined by /gc/heap/tiny/allocs:objects, only tiny blocks.
        
        /gc/heap/frees-by-size:bytes
        	Distribution of freed heap allocations by approximate size.
        	Bucket counts increase monotonically. Note that this does not
        	include tiny objects as defined by /gc/heap/tiny/allocs:objects,
        	only tiny blocks.
        
        /gc/heap/frees:bytes
        	Cumulative sum of heap memory freed by the garbage collector.
        
        /gc/heap/frees:objects
        	Cumulative count of heap allocations whose storage was freed
        	by the garbage collector. Note that this does not include tiny
        	objects as defined by /gc/heap/tiny/allocs:objects, only tiny
        	blocks.
        
        /gc/heap/goal:bytes
        	Heap size target for the end of the GC cycle.
        
        /gc/heap/live:bytes
        	Heap memory occupied by live objects that were marked by the
        	previous GC.
        
        /gc/heap/objects:objects
        	Number of objects, live or unswept, occupying heap memory.
        
        /gc/heap/tiny/allocs:objects
        	Count of small allocations that are packed together into blocks.
        	These allocations are counted separately from other allocations
        	because each individual allocation is not tracked by the
        	runtime, only their block. Each block is already accounted for
        	in allocs-by-size and frees-by-size.
        
        /gc/limiter/last-enabled:gc-cycle
        	GC cycle the last time the GC CPU limiter was enabled.
        	This metric is useful for diagnosing the root cause of an
        	out-of-memory error, because the limiter trades memory for CPU
        	time when the GC's CPU time gets too high. This is most likely
        	to occur with use of SetMemoryLimit. The first GC cycle is cycle
        	1, so a value of 0 indicates that it was never enabled.
        
        /gc/pauses:seconds
        	Deprecated. Prefer the identical /sched/pauses/total/gc:seconds.
        
        /gc/scan/globals:bytes
        	The total amount of global variable space that is scannable.
        
        /gc/scan/heap:bytes
        	The total amount of heap space that is scannable.
        
        /gc/scan/stack:bytes
        	The number of bytes of stack that were scanned last GC cycle.
        
        /gc/scan/total:bytes
        	The total amount space that is scannable. Sum of all metrics in
        	/gc/scan.
        
        /gc/stack/starting-size:bytes
        	The stack size of new goroutines.
        
        /godebug/non-default-behavior/execerrdot:events
        	The number of non-default behaviors executed by the os/exec
        	package due to a non-default GODEBUG=execerrdot=... setting.
        
        /godebug/non-default-behavior/gocachehash:events
        	The number of non-default behaviors executed by the cmd/go
        	package due to a non-default GODEBUG=gocachehash=... setting.
        
        /godebug/non-default-behavior/gocachetest:events
        	The number of non-default behaviors executed by the cmd/go
        	package due to a non-default GODEBUG=gocachetest=... setting.
        
        /godebug/non-default-behavior/gocacheverify:events
        	The number of non-default behaviors executed by the cmd/go
        	package due to a non-default GODEBUG=gocacheverify=... setting.
        
        /godebug/non-default-behavior/gotypesalias:events
        	The number of non-default behaviors executed by the go/types
        	package due to a non-default GODEBUG=gotypesalias=... setting.
        
        /godebug/non-default-behavior/http2client:events
        	The number of non-default behaviors executed by the net/http
        	package due to a non-default GODEBUG=http2client=... setting.
        
        /godebug/non-default-behavior/http2server:events
        	The number of non-default behaviors executed by the net/http
        	package due to a non-default GODEBUG=http2server=... setting.
        
        /godebug/non-default-behavior/httplaxcontentlength:events
        	The number of non-default behaviors executed by the net/http
        	package due to a non-default GODEBUG=httplaxcontentlength=...
        	setting.
        
        /godebug/non-default-behavior/httpmuxgo121:events
        	The number of non-default behaviors executed by the net/http
        	package due to a non-default GODEBUG=httpmuxgo121=... setting.
        
        /godebug/non-default-behavior/installgoroot:events
        	The number of non-default behaviors executed by the go/build
        	package due to a non-default GODEBUG=installgoroot=... setting.
        
        /godebug/non-default-behavior/jstmpllitinterp:events
        	The number of non-default behaviors executed by
        	the html/template package due to a non-default
        	GODEBUG=jstmpllitinterp=... setting.
        
        /godebug/non-default-behavior/multipartmaxheaders:events
        	The number of non-default behaviors executed by
        	the mime/multipart package due to a non-default
        	GODEBUG=multipartmaxheaders=... setting.
        
        /godebug/non-default-behavior/multipartmaxparts:events
        	The number of non-default behaviors executed by
        	the mime/multipart package due to a non-default
        	GODEBUG=multipartmaxparts=... setting.
        
        /godebug/non-default-behavior/multipathtcp:events
        	The number of non-default behaviors executed by the net package
        	due to a non-default GODEBUG=multipathtcp=... setting.
        
        /godebug/non-default-behavior/panicnil:events
        	The number of non-default behaviors executed by the runtime
        	package due to a non-default GODEBUG=panicnil=... setting.
        
        /godebug/non-default-behavior/randautoseed:events
        	The number of non-default behaviors executed by the math/rand
        	package due to a non-default GODEBUG=randautoseed=... setting.
        
        /godebug/non-default-behavior/tarinsecurepath:events
        	The number of non-default behaviors executed by the archive/tar
        	package due to a non-default GODEBUG=tarinsecurepath=...
        	setting.
        
        /godebug/non-default-behavior/tls10server:events
        	The number of non-default behaviors executed by the crypto/tls
        	package due to a non-default GODEBUG=tls10server=... setting.
        
        /godebug/non-default-behavior/tlsmaxrsasize:events
        	The number of non-default behaviors executed by the crypto/tls
        	package due to a non-default GODEBUG=tlsmaxrsasize=... setting.
        
        /godebug/non-default-behavior/tlsrsakex:events
        	The number of non-default behaviors executed by the crypto/tls
        	package due to a non-default GODEBUG=tlsrsakex=... setting.
        
        /godebug/non-default-behavior/tlsunsafeekm:events
        	The number of non-default behaviors executed by the crypto/tls
        	package due to a non-default GODEBUG=tlsunsafeekm=... setting.
        
        /godebug/non-default-behavior/x509sha1:events
        	The number of non-default behaviors executed by the crypto/x509
        	package due to a non-default GODEBUG=x509sha1=... setting.
        
        /godebug/non-default-behavior/x509usefallbackroots:events
        	The number of non-default behaviors executed by the crypto/x509
        	package due to a non-default GODEBUG=x509usefallbackroots=...
        	setting.
        
        /godebug/non-default-behavior/x509usepolicies:events
        	The number of non-default behaviors executed by the crypto/x509
        	package due to a non-default GODEBUG=x509usepolicies=...
        	setting.
        
        /godebug/non-default-behavior/zipinsecurepath:events
        	The number of non-default behaviors executed by the archive/zip
        	package due to a non-default GODEBUG=zipinsecurepath=...
        	setting.
        
        /memory/classes/heap/free:bytes
        	Memory that is completely free and eligible to be returned to
        	the underlying system, but has not been. This metric is the
        	runtime's estimate of free address space that is backed by
        	physical memory.
        
        /memory/classes/heap/objects:bytes
        	Memory occupied by live objects and dead objects that have not
        	yet been marked free by the garbage collector.
        
        /memory/classes/heap/released:bytes
        	Memory that is completely free and has been returned to the
        	underlying system. This metric is the runtime's estimate of free
        	address space that is still mapped into the process, but is not
        	backed by physical memory.
        
        /memory/classes/heap/stacks:bytes
        	Memory allocated from the heap that is reserved for stack space,
        	whether or not it is currently in-use. Currently, this
        	represents all stack memory for goroutines. It also includes all
        	OS thread stacks in non-cgo programs. Note that stacks may be
        	allocated differently in the future, and this may change.
        
        /memory/classes/heap/unused:bytes
        	Memory that is reserved for heap objects but is not currently
        	used to hold heap objects.
        
        /memory/classes/metadata/mcache/free:bytes
        	Memory that is reserved for runtime mcache structures, but not
        	in-use.
        
        /memory/classes/metadata/mcache/inuse:bytes
        	Memory that is occupied by runtime mcache structures that are
        	currently being used.
        
        /memory/classes/metadata/mspan/free:bytes
        	Memory that is reserved for runtime mspan structures, but not
        	in-use.
        
        /memory/classes/metadata/mspan/inuse:bytes
        	Memory that is occupied by runtime mspan structures that are
        	currently being used.
        
        /memory/classes/metadata/other:bytes
        	Memory that is reserved for or used to hold runtime metadata.
        
        /memory/classes/os-stacks:bytes
        	Stack memory allocated by the underlying operating system.
        	In non-cgo programs this metric is currently zero. This may
        	change in the future.In cgo programs this metric includes
        	OS thread stacks allocated directly from the OS. Currently,
        	this only accounts for one stack in c-shared and c-archive build
        	modes, and other sources of stacks from the OS are not measured.
        	This too may change in the future.
        
        /memory/classes/other:bytes
        	Memory used by execution trace buffers, structures for debugging
        	the runtime, finalizer and profiler specials, and more.
        
        /memory/classes/profiling/buckets:bytes
        	Memory that is used by the stack trace hash map used for
        	profiling.
        
        /memory/classes/total:bytes
        	All memory mapped by the Go runtime into the current process
        	as read-write. Note that this does not include memory mapped
        	by code called via cgo or via the syscall package. Sum of all
        	metrics in /memory/classes.
        
        /sched/gomaxprocs:threads
        	The current runtime.GOMAXPROCS setting, or the number of
        	operating system threads that can execute user-level Go code
        	simultaneously.
        
        /sched/goroutines:goroutines
        	Count of live goroutines.
        
        /sched/latencies:seconds
        	Distribution of the time goroutines have spent in the scheduler
        	in a runnable state before actually running. Bucket counts
        	increase monotonically.
        
        /sched/pauses/stopping/gc:seconds
        	Distribution of individual GC-related stop-the-world stopping
        	latencies. This is the time it takes from deciding to stop the
        	world until all Ps are stopped. This is a subset of the total
        	GC-related stop-the-world time (/sched/pauses/total/gc:seconds).
        	During this time, some threads may be executing. Bucket counts
        	increase monotonically.
        
        /sched/pauses/stopping/other:seconds
        	Distribution of individual non-GC-related stop-the-world
        	stopping latencies. This is the time it takes from deciding
        	to stop the world until all Ps are stopped. This is a
        	subset of the total non-GC-related stop-the-world time
        	(/sched/pauses/total/other:seconds). During this time, some
        	threads may be executing. Bucket counts increase monotonically.
        
        /sched/pauses/total/gc:seconds
        	Distribution of individual GC-related stop-the-world pause
        	latencies. This is the time from deciding to stop the world
        	until the world is started again. Some of this time is spent
        	getting all threads to stop (this is measured directly in
        	/sched/pauses/stopping/gc:seconds), during which some threads
        	may still be running. Bucket counts increase monotonically.
        
        /sched/pauses/total/other:seconds
        	Distribution of individual non-GC-related stop-the-world
        	pause latencies. This is the time from deciding to stop the
        	world until the world is started again. Some of this time
        	is spent getting all threads to stop (measured directly in
        	/sched/pauses/stopping/other:seconds). Bucket counts increase
        	monotonically.
        
        /sync/mutex/wait/total:seconds
        	Approximate cumulative time goroutines have spent blocked on a
        	sync.Mutex, sync.RWMutex, or runtime-internal lock. This metric
        	is useful for identifying global changes in lock contention.
        	Collect a mutex or block profile using the runtime/pprof package
        	for more detailed contention data.
        

        func Read

        func Read(m []Sample)

        Read populates each Value field in the given slice of metric samples.

        Desired metrics should be present in the slice with the appropriate name. The user of this API is encouraged to re-use the same slice between calls for efficiency, but is not required to do so.

        Note that re-use has some caveats. Notably, Values should not be read or manipulated while a Read with that value is outstanding; that is a data race. This property includes pointer-typed Values (for example, Float64Histogram) whose underlying storage will be reused by Read when possible. To safely use such values in a concurrent setting, all data must be deep-copied.

        It is safe to execute multiple Read calls concurrently, but their arguments must share no underlying memory. When in doubt, create a new []Sample from scratch, which is always safe, though may be inefficient.

        Sample values with names not appearing in All will have their Value populated as KindBad to indicate that the name is unknown.

        Example (ReadingAllMetrics)

        Code:

        // Get descriptions for all supported metrics.
        descs := metrics.All()
        
        // Create a sample for each metric.
        samples := make([]metrics.Sample, len(descs))
        for i := range samples {
            samples[i].Name = descs[i].Name
        }
        
        // Sample the metrics. Re-use the samples slice if you can!
        metrics.Read(samples)
        
        // Iterate over all results.
        for _, sample := range samples {
            // Pull out the name and value.
            name, value := sample.Name, sample.Value
        
            // Handle each sample.
            switch value.Kind() {
            case metrics.KindUint64:
                fmt.Printf("%s: %d\n", name, value.Uint64())
            case metrics.KindFloat64:
                fmt.Printf("%s: %f\n", name, value.Float64())
            case metrics.KindFloat64Histogram:
                // The histogram may be quite large, so let's just pull out
                // a crude estimate for the median for the sake of this example.
                fmt.Printf("%s: %f\n", name, medianBucket(value.Float64Histogram()))
            case metrics.KindBad:
                // This should never happen because all metrics are supported
                // by construction.
                panic("bug in runtime/metrics package!")
            default:
                // This may happen as new metrics get added.
                //
                // The safest thing to do here is to simply log it somewhere
                // as something to look into, but ignore it for now.
                // In the worst case, you might temporarily miss out on a new metric.
                fmt.Printf("%s: unexpected metric Kind: %v\n", name, value.Kind())
            }
        }
        

        Example (ReadingOneMetric)

        Code:

        // Name of the metric we want to read.
        const myMetric = "/memory/classes/heap/free:bytes"
        
        // Create a sample for the metric.
        sample := make([]metrics.Sample, 1)
        sample[0].Name = myMetric
        
        // Sample the metric.
        metrics.Read(sample)
        
        // Check if the metric is actually supported.
        // If it's not, the resulting value will always have
        // kind KindBad.
        if sample[0].Value.Kind() == metrics.KindBad {
            panic(fmt.Sprintf("metric %q no longer supported", myMetric))
        }
        
        // Handle the result.
        //
        // It's OK to assume a particular Kind for a metric;
        // they're guaranteed not to change.
        freeBytes := sample[0].Value.Uint64()
        
        fmt.Printf("free but not released memory: %d\n", freeBytes)
        

        type Description

        Description describes a runtime metric.

        type Description struct {
            // Name is the full name of the metric which includes the unit.
            //
            // The format of the metric may be described by the following regular expression.
            //
            // 	^(?P<name>/[^:]+):(?P<unit>[^:*/]+(?:[*/][^:*/]+)*)$
            //
            // The format splits the name into two components, separated by a colon: a path which always
            // starts with a /, and a machine-parseable unit. The name may contain any valid Unicode
            // codepoint in between / characters, but by convention will try to stick to lowercase
            // characters and hyphens. An example of such a path might be "/memory/heap/free".
            //
            // The unit is by convention a series of lowercase English unit names (singular or plural)
            // without prefixes delimited by '*' or '/'. The unit names may contain any valid Unicode
            // codepoint that is not a delimiter.
            // Examples of units might be "seconds", "bytes", "bytes/second", "cpu-seconds",
            // "byte*cpu-seconds", and "bytes/second/second".
            //
            // For histograms, multiple units may apply. For instance, the units of the buckets and
            // the count. By convention, for histograms, the units of the count are always "samples"
            // with the type of sample evident by the metric's name, while the unit in the name
            // specifies the buckets' unit.
            //
            // A complete name might look like "/memory/heap/free:bytes".
            Name string
        
            // Description is an English language sentence describing the metric.
            Description string
        
            // Kind is the kind of value for this metric.
            //
            // The purpose of this field is to allow users to filter out metrics whose values are
            // types which their application may not understand.
            Kind ValueKind
        
            // Cumulative is whether or not the metric is cumulative. If a cumulative metric is just
            // a single number, then it increases monotonically. If the metric is a distribution,
            // then each bucket count increases monotonically.
            //
            // This flag thus indicates whether or not it's useful to compute a rate from this value.
            Cumulative bool
        }
        

        func All

        func All() []Description

        All returns a slice of containing metric descriptions for all supported metrics.

        type Float64Histogram

        Float64Histogram represents a distribution of float64 values.

        type Float64Histogram struct {
            // Counts contains the weights for each histogram bucket.
            //
            // Given N buckets, Count[n] is the weight of the range
            // [bucket[n], bucket[n+1]), for 0 <= n < N.
            Counts []uint64
        
            // Buckets contains the boundaries of the histogram buckets, in increasing order.
            //
            // Buckets[0] is the inclusive lower bound of the minimum bucket while
            // Buckets[len(Buckets)-1] is the exclusive upper bound of the maximum bucket.
            // Hence, there are len(Buckets)-1 counts. Furthermore, len(Buckets) != 1, always,
            // since at least two boundaries are required to describe one bucket (and 0
            // boundaries are used to describe 0 buckets).
            //
            // Buckets[0] is permitted to have value -Inf and Buckets[len(Buckets)-1] is
            // permitted to have value Inf.
            //
            // For a given metric name, the value of Buckets is guaranteed not to change
            // between calls until program exit.
            //
            // This slice value is permitted to alias with other Float64Histograms' Buckets
            // fields, so the values within should only ever be read. If they need to be
            // modified, the user must make a copy.
            Buckets []float64
        }
        

        type Sample

        Sample captures a single metric sample.

        type Sample struct {
            // Name is the name of the metric sampled.
            //
            // It must correspond to a name in one of the metric descriptions
            // returned by All.
            Name string
        
            // Value is the value of the metric sample.
            Value Value
        }
        

        type Value

        Value represents a metric value returned by the runtime.

        type Value struct {
            // contains filtered or unexported fields
        }
        

        func (Value) Float64

        func (v Value) Float64() float64

        Float64 returns the internal float64 value for the metric.

        If v.Kind() != KindFloat64, this method panics.

        func (Value) Float64Histogram

        func (v Value) Float64Histogram() *Float64Histogram

        Float64Histogram returns the internal *Float64Histogram value for the metric.

        If v.Kind() != KindFloat64Histogram, this method panics.

        func (Value) Kind

        func (v Value) Kind() ValueKind

        Kind returns the tag representing the kind of value this is.

        func (Value) Uint64

        func (v Value) Uint64() uint64

        Uint64 returns the internal uint64 value for the metric.

        If v.Kind() != KindUint64, this method panics.

        type ValueKind

        ValueKind is a tag for a metric Value which indicates its type.

        type ValueKind int
        const (
            // KindBad indicates that the Value has no type and should not be used.
            KindBad ValueKind = iota
        
            // KindUint64 indicates that the type of the Value is a uint64.
            KindUint64
        
            // KindFloat64 indicates that the type of the Value is a float64.
            KindFloat64
        
            // KindFloat64Histogram indicates that the type of the Value is a *Float64Histogram.
            KindFloat64Histogram
        )
        msan - Go Documentation Server
        ...

        Command msan

        pprof - Go Documentation Server
        ...

        Package pprof

        import "runtime/pprof"
        Overview
        Index

        Overview ▾

        Package pprof writes runtime profiling data in the format expected by the pprof visualization tool.

        Profiling a Go program

        The first step to profiling a Go program is to enable profiling. Support for profiling benchmarks built with the standard testing package is built into go test. For example, the following command runs benchmarks in the current directory and writes the CPU and memory profiles to cpu.prof and mem.prof:

        go test -cpuprofile cpu.prof -memprofile mem.prof -bench .
        

        To add equivalent profiling support to a standalone program, add code like the following to your main function:

        var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`")
        var memprofile = flag.String("memprofile", "", "write memory profile to `file`")
        
        func main() {
            flag.Parse()
            if *cpuprofile != "" {
                f, err := os.Create(*cpuprofile)
                if err != nil {
                    log.Fatal("could not create CPU profile: ", err)
                }
                defer f.Close() // error handling omitted for example
                if err := pprof.StartCPUProfile(f); err != nil {
                    log.Fatal("could not start CPU profile: ", err)
                }
                defer pprof.StopCPUProfile()
            }
        
            // ... rest of the program ...
        
            if *memprofile != "" {
                f, err := os.Create(*memprofile)
                if err != nil {
                    log.Fatal("could not create memory profile: ", err)
                }
                defer f.Close() // error handling omitted for example
                runtime.GC() // get up-to-date statistics
                if err := pprof.WriteHeapProfile(f); err != nil {
                    log.Fatal("could not write memory profile: ", err)
                }
            }
        }
        

        There is also a standard HTTP interface to profiling data. Adding the following line will install handlers under the /debug/pprof/ URL to download live profiles:

        import _ "net/http/pprof"
        

        See the net/http/pprof package for more details.

        Profiles can then be visualized with the pprof tool:

        go tool pprof cpu.prof
        

        There are many commands available from the pprof command line. Commonly used commands include "top", which prints a summary of the top program hot-spots, and "web", which opens an interactive graph of hot-spots and their call graphs. Use "help" for information on all pprof commands.

        For more information about pprof, see https://github.com/google/pprof/blob/main/doc/README.md.

        func Do

        func Do(ctx context.Context, labels LabelSet, f func(context.Context))

        Do calls f with a copy of the parent context with the given labels added to the parent's label map. Goroutines spawned while executing f will inherit the augmented label-set. Each key/value pair in labels is inserted into the label map in the order provided, overriding any previous value for the same key. The augmented label map will be set for the duration of the call to f and restored once f returns.

        func ForLabels

        func ForLabels(ctx context.Context, f func(key, value string) bool)

        ForLabels invokes f with each label set on the context. The function f should return true to continue iteration or false to stop iteration early.

        func Label

        func Label(ctx context.Context, key string) (string, bool)

        Label returns the value of the label with the given key on ctx, and a boolean indicating whether that label exists.

        func SetGoroutineLabels

        func SetGoroutineLabels(ctx context.Context)

        SetGoroutineLabels sets the current goroutine's labels to match ctx. A new goroutine inherits the labels of the goroutine that created it. This is a lower-level API than Do, which should be used instead when possible.

        func StartCPUProfile

        func StartCPUProfile(w io.Writer) error

        StartCPUProfile enables CPU profiling for the current process. While profiling, the profile will be buffered and written to w. StartCPUProfile returns an error if profiling is already enabled.

        On Unix-like systems, StartCPUProfile does not work by default for Go code built with -buildmode=c-archive or -buildmode=c-shared. StartCPUProfile relies on the SIGPROF signal, but that signal will be delivered to the main program's SIGPROF signal handler (if any) not to the one used by Go. To make it work, call os/signal.Notify for syscall.SIGPROF, but note that doing so may break any profiling being done by the main program.

        func StopCPUProfile

        func StopCPUProfile()

        StopCPUProfile stops the current CPU profile, if any. StopCPUProfile only returns after all the writes for the profile have completed.

        func WithLabels

        func WithLabels(ctx context.Context, labels LabelSet) context.Context

        WithLabels returns a new context.Context with the given labels added. A label overwrites a prior label with the same key.

        func WriteHeapProfile

        func WriteHeapProfile(w io.Writer) error

        WriteHeapProfile is shorthand for Lookup("heap").WriteTo(w, 0). It is preserved for backwards compatibility.

        type LabelSet

        LabelSet is a set of labels.

        type LabelSet struct {
            // contains filtered or unexported fields
        }
        

        func Labels

        func Labels(args ...string) LabelSet

        Labels takes an even number of strings representing key-value pairs and makes a LabelSet containing them. A label overwrites a prior label with the same key. Currently only the CPU and goroutine profiles utilize any labels information. See https://golang.org/issue/23458 for details.

        type Profile

        A Profile is a collection of stack traces showing the call sequences that led to instances of a particular event, such as allocation. Packages can create and maintain their own profiles; the most common use is for tracking resources that must be explicitly closed, such as files or network connections.

        A Profile's methods can be called from multiple goroutines simultaneously.

        Each Profile has a unique name. A few profiles are predefined:

        goroutine    - stack traces of all current goroutines
        heap         - a sampling of memory allocations of live objects
        allocs       - a sampling of all past memory allocations
        threadcreate - stack traces that led to the creation of new OS threads
        block        - stack traces that led to blocking on synchronization primitives
        mutex        - stack traces of holders of contended mutexes
        

        These predefined profiles maintain themselves and panic on an explicit Profile.Add or Profile.Remove method call.

        The CPU profile is not available as a Profile. It has a special API, the StartCPUProfile and StopCPUProfile functions, because it streams output to a writer during profiling.

        Heap profile

        The heap profile reports statistics as of the most recently completed garbage collection; it elides more recent allocation to avoid skewing the profile away from live data and toward garbage. If there has been no garbage collection at all, the heap profile reports all known allocations. This exception helps mainly in programs running without garbage collection enabled, usually for debugging purposes.

        The heap profile tracks both the allocation sites for all live objects in the application memory and for all objects allocated since the program start. Pprof's -inuse_space, -inuse_objects, -alloc_space, and -alloc_objects flags select which to display, defaulting to -inuse_space (live objects, scaled by size).

        Allocs profile

        The allocs profile is the same as the heap profile but changes the default pprof display to -alloc_space, the total number of bytes allocated since the program began (including garbage-collected bytes).

        Block profile

        The block profile tracks time spent blocked on synchronization primitives, such as sync.Mutex, sync.RWMutex, sync.WaitGroup, sync.Cond, and channel send/receive/select.

        Stack traces correspond to the location that blocked (for example, sync.Mutex.Lock).

        Sample values correspond to cumulative time spent blocked at that stack trace, subject to time-based sampling specified by runtime.SetBlockProfileRate.

        Mutex profile

        The mutex profile tracks contention on mutexes, such as sync.Mutex, sync.RWMutex, and runtime-internal locks.

        Stack traces correspond to the end of the critical section causing contention. For example, a lock held for a long time while other goroutines are waiting to acquire the lock will report contention when the lock is finally unlocked (that is, at sync.Mutex.Unlock).

        Sample values correspond to the approximate cumulative time other goroutines spent blocked waiting for the lock, subject to event-based sampling specified by runtime.SetMutexProfileFraction. For example, if a caller holds a lock for 1s while 5 other goroutines are waiting for the entire second to acquire the lock, its unlock call stack will report 5s of contention.

        Runtime-internal locks are always reported at the location "runtime._LostContendedRuntimeLock". More detailed stack traces for runtime-internal locks can be obtained by setting `GODEBUG=runtimecontentionstacks=1` (see package runtime docs for caveats).

        type Profile struct {
            // contains filtered or unexported fields
        }
        

        func Lookup

        func Lookup(name string) *Profile

        Lookup returns the profile with the given name, or nil if no such profile exists.

        func NewProfile

        func NewProfile(name string) *Profile

        NewProfile creates a new profile with the given name. If a profile with that name already exists, NewProfile panics. The convention is to use a 'import/path.' prefix to create separate name spaces for each package. For compatibility with various tools that read pprof data, profile names should not contain spaces.

        func Profiles

        func Profiles() []*Profile

        Profiles returns a slice of all the known profiles, sorted by name.

        func (*Profile) Add

        func (p *Profile) Add(value any, skip int)

        Add adds the current execution stack to the profile, associated with value. Add stores value in an internal map, so value must be suitable for use as a map key and will not be garbage collected until the corresponding call to Profile.Remove. Add panics if the profile already contains a stack for value.

        The skip parameter has the same meaning as runtime.Caller's skip and controls where the stack trace begins. Passing skip=0 begins the trace in the function calling Add. For example, given this execution stack:

        Add
        called from rpc.NewClient
        called from mypkg.Run
        called from main.main
        

        Passing skip=0 begins the stack trace at the call to Add inside rpc.NewClient. Passing skip=1 begins the stack trace at the call to NewClient inside mypkg.Run.

        func (*Profile) Count

        func (p *Profile) Count() int

        Count returns the number of execution stacks currently in the profile.

        func (*Profile) Name

        func (p *Profile) Name() string

        Name returns this profile's name, which can be passed to Lookup to reobtain the profile.

        func (*Profile) Remove

        func (p *Profile) Remove(value any)

        Remove removes the execution stack associated with value from the profile. It is a no-op if the value is not in the profile.

        func (*Profile) WriteTo

        func (p *Profile) WriteTo(w io.Writer, debug int) error

        WriteTo writes a pprof-formatted snapshot of the profile to w. If a write to w returns an error, WriteTo returns that error. Otherwise, WriteTo returns nil.

        The debug parameter enables additional output. Passing debug=0 writes the gzip-compressed protocol buffer described in https://github.com/google/pprof/tree/master/proto#overview. Passing debug=1 writes the legacy text format with comments translating addresses to function names and line numbers, so that a programmer can read the profile without tools.

        The predefined profiles may assign meaning to other debug values; for example, when printing the "goroutine" profile, debug=2 means to print the goroutine stacks in the same form that a Go program uses when dying due to an unrecovered panic.

        Bugs

        race - Go Documentation Server
        ...

        Package race

        import "runtime/race"
        Overview
        Index
        Subdirectories

        Overview ▾

        Package race implements data race detection logic. No public interface is provided. For details about the race detector see https://golang.org/doc/articles/race_detector.html

        Index ▾

        Package files

        doc.go race_v1_amd64.go

        Subdirectories

        Name Synopsis
        ..
        trace - Go Documentation Server
        ...

        Package trace

        import "runtime/trace"
        Overview
        Index
        Examples

        Overview ▾

        Package trace contains facilities for programs to generate traces for the Go execution tracer.

        Tracing runtime activities

        The execution trace captures a wide range of execution events such as goroutine creation/blocking/unblocking, syscall enter/exit/block, GC-related events, changes of heap size, processor start/stop, etc. When CPU profiling is active, the execution tracer makes an effort to include those samples as well. A precise nanosecond-precision timestamp and a stack trace is captured for most events. The generated trace can be interpreted using `go tool trace`.

        Support for tracing tests and benchmarks built with the standard testing package is built into `go test`. For example, the following command runs the test in the current directory and writes the trace file (trace.out).

        go test -trace=trace.out
        

        This runtime/trace package provides APIs to add equivalent tracing support to a standalone program. See the Example that demonstrates how to use this API to enable tracing.

        There is also a standard HTTP interface to trace data. Adding the following line will install a handler under the /debug/pprof/trace URL to download a live trace:

        import _ "net/http/pprof"
        

        See the net/http/pprof package for more details about all of the debug endpoints installed by this import.

        User annotation

        Package trace provides user annotation APIs that can be used to log interesting events during execution.

        There are three types of user annotations: log messages, regions, and tasks.

        Log emits a timestamped message to the execution trace along with additional information such as the category of the message and which goroutine called Log. The execution tracer provides UIs to filter and group goroutines using the log category and the message supplied in Log.

        A region is for logging a time interval during a goroutine's execution. By definition, a region starts and ends in the same goroutine. Regions can be nested to represent subintervals. For example, the following code records four regions in the execution trace to trace the durations of sequential steps in a cappuccino making operation.

        trace.WithRegion(ctx, "makeCappuccino", func() {
        
           // orderID allows to identify a specific order
           // among many cappuccino order region records.
           trace.Log(ctx, "orderID", orderID)
        
           trace.WithRegion(ctx, "steamMilk", steamMilk)
           trace.WithRegion(ctx, "extractCoffee", extractCoffee)
           trace.WithRegion(ctx, "mixMilkCoffee", mixMilkCoffee)
        })
        

        A task is a higher-level component that aids tracing of logical operations such as an RPC request, an HTTP request, or an interesting local operation which may require multiple goroutines working together. Since tasks can involve multiple goroutines, they are tracked via a context.Context object. NewTask creates a new task and embeds it in the returned context.Context object. Log messages and regions are attached to the task, if any, in the Context passed to Log and WithRegion.

        For example, assume that we decided to froth milk, extract coffee, and mix milk and coffee in separate goroutines. With a task, the trace tool can identify the goroutines involved in a specific cappuccino order.

        ctx, task := trace.NewTask(ctx, "makeCappuccino")
        trace.Log(ctx, "orderID", orderID)
        
        milk := make(chan bool)
        espresso := make(chan bool)
        
        go func() {
                trace.WithRegion(ctx, "steamMilk", steamMilk)
                milk <- true
        }()
        go func() {
                trace.WithRegion(ctx, "extractCoffee", extractCoffee)
                espresso <- true
        }()
        go func() {
                defer task.End() // When assemble is done, the order is complete.
                <-espresso
                <-milk
                trace.WithRegion(ctx, "mixMilkCoffee", mixMilkCoffee)
        }()
        

        The trace tool computes the latency of a task by measuring the time between the task creation and the task end and provides latency distributions for each task type found in the trace.

        Example

        Example demonstrates the use of the trace package to trace the execution of a Go program. The trace output will be written to the file trace.out

        Code:

        package trace_test
        
        import (
            "fmt"
            "log"
            "os"
            "runtime/trace"
        )
        
        // Example demonstrates the use of the trace package to trace
        // the execution of a Go program. The trace output will be
        // written to the file trace.out
        func Example() {
            f, err := os.Create("trace.out")
            if err != nil {
                log.Fatalf("failed to create trace output file: %v", err)
            }
            defer func() {
                if err := f.Close(); err != nil {
                    log.Fatalf("failed to close trace file: %v", err)
                }
            }()
        
            if err := trace.Start(f); err != nil {
                log.Fatalf("failed to start trace: %v", err)
            }
            defer trace.Stop()
        
            // your program here
            RunMyProgram()
        }
        
        func RunMyProgram() {
            fmt.Printf("this function will be traced")
        }
        

        func IsEnabled

        func IsEnabled() bool

        IsEnabled reports whether tracing is enabled. The information is advisory only. The tracing status may have changed by the time this function returns.

        func Log

        func Log(ctx context.Context, category, message string)

        Log emits a one-off event with the given category and message. Category can be empty and the API assumes there are only a handful of unique categories in the system.

        func Logf

        func Logf(ctx context.Context, category, format string, args ...any)

        Logf is like Log, but the value is formatted using the specified format spec.

        func Start

        func Start(w io.Writer) error

        Start enables tracing for the current program. While tracing, the trace will be buffered and written to w. Start returns an error if tracing is already enabled.

        func Stop

        func Stop()

        Stop stops the current tracing, if any. Stop only returns after all the writes for the trace have completed.

        func WithRegion

        func WithRegion(ctx context.Context, regionType string, fn func())

        WithRegion starts a region associated with its calling goroutine, runs fn, and then ends the region. If the context carries a task, the region is associated with the task. Otherwise, the region is attached to the background task.

        The regionType is used to classify regions, so there should be only a handful of unique region types.

        type Region

        Region is a region of code whose execution time interval is traced.

        type Region struct {
            // contains filtered or unexported fields
        }
        

        func StartRegion

        func StartRegion(ctx context.Context, regionType string) *Region

        StartRegion starts a region and returns it. The returned Region's Region.End method must be called from the same goroutine where the region was started. Within each goroutine, regions must nest. That is, regions started after this region must be ended before this region can be ended. Recommended usage is

        defer trace.StartRegion(ctx, "myTracedRegion").End()
        

        func (*Region) End

        func (r *Region) End()

        End marks the end of the traced code region.

        type Task

        Task is a data type for tracing a user-defined, logical operation.

        type Task struct {
            // contains filtered or unexported fields
        }
        

        func NewTask

        func NewTask(pctx context.Context, taskType string) (ctx context.Context, task *Task)

        NewTask creates a task instance with the type taskType and returns it along with a Context that carries the task. If the input context contains a task, the new task is its subtask.

        The taskType is used to classify task instances. Analysis tools like the Go execution tracer may assume there are only a bounded number of unique task types in the system.

        The returned Task's Task.End method is used to mark the task's end. The trace tool measures task latency as the time between task creation and when the End method is called, and provides the latency distribution per task type. If the End method is called multiple times, only the first call is used in the latency measurement.

        ctx, task := trace.NewTask(ctx, "awesomeTask")
        trace.WithRegion(ctx, "preparation", prepWork)
        // preparation of the task
        go func() {  // continue processing the task in a separate goroutine.
            defer task.End()
            trace.WithRegion(ctx, "remainingWork", remainingWork)
        }()
        

        func (*Task) End

        func (t *Task) End()

        End marks the end of the operation represented by the Task.

        slices - Go Documentation Server
        ...

        Package slices

        import "slices"
        Overview
        Index
        Examples

        Overview ▾

        Package slices defines various functions useful with slices of any type.

        Index ▾

        func BinarySearch[S ~[]E, E cmp.Ordered](x S, target E) (int, bool)
        func BinarySearchFunc[S ~[]E, E, T any](x S, target T, cmp func(E, T) int) (int, bool)
        func Clip[S ~[]E, E any](s S) S
        func Clone[S ~[]E, E any](s S) S
        func Compact[S ~[]E, E comparable](s S) S
        func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S
        func Compare[S ~[]E, E cmp.Ordered](s1, s2 S) int
        func CompareFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, cmp func(E1, E2) int) int
        func Concat[S ~[]E, E any](slices ...S) S
        func Contains[S ~[]E, E comparable](s S, v E) bool
        func ContainsFunc[S ~[]E, E any](s S, f func(E) bool) bool
        func Delete[S ~[]E, E any](s S, i, j int) S
        func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S
        func Equal[S ~[]E, E comparable](s1, s2 S) bool
        func EqualFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, eq func(E1, E2) bool) bool
        func Grow[S ~[]E, E any](s S, n int) S
        func Index[S ~[]E, E comparable](s S, v E) int
        func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int
        func Insert[S ~[]E, E any](s S, i int, v ...E) S
        func IsSorted[S ~[]E, E cmp.Ordered](x S) bool
        func IsSortedFunc[S ~[]E, E any](x S, cmp func(a, b E) int) bool
        func Max[S ~[]E, E cmp.Ordered](x S) E
        func MaxFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E
        func Min[S ~[]E, E cmp.Ordered](x S) E
        func MinFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E
        func Replace[S ~[]E, E any](s S, i, j int, v ...E) S
        func Reverse[S ~[]E, E any](s S)
        func Sort[S ~[]E, E cmp.Ordered](x S)
        func SortFunc[S ~[]E, E any](x S, cmp func(a, b E) int)
        func SortStableFunc[S ~[]E, E any](x S, cmp func(a, b E) int)

        Package files

        slices.go sort.go zsortanyfunc.go zsortordered.go

        func BinarySearch

        func BinarySearch[S ~[]E, E cmp.Ordered](x S, target E) (int, bool)

        BinarySearch searches for target in a sorted slice and returns the position where target is found, or the position where target would appear in the sort order; it also returns a bool saying whether the target is really found in the slice. The slice must be sorted in increasing order.

        Example

        Code:

        names := []string{"Alice", "Bob", "Vera"}
        n, found := slices.BinarySearch(names, "Vera")
        fmt.Println("Vera:", n, found)
        n, found = slices.BinarySearch(names, "Bill")
        fmt.Println("Bill:", n, found)
        

        Output:

        Vera: 2 true
        Bill: 1 false
        

        func BinarySearchFunc

        func BinarySearchFunc[S ~[]E, E, T any](x S, target T, cmp func(E, T) int) (int, bool)

        BinarySearchFunc works like BinarySearch, but uses a custom comparison function. The slice must be sorted in increasing order, where "increasing" is defined by cmp. cmp should return 0 if the slice element matches the target, a negative number if the slice element precedes the target, or a positive number if the slice element follows the target. cmp must implement the same ordering as the slice, such that if cmp(a, t) < 0 and cmp(b, t) >= 0, then a must precede b in the slice.

        Example

        Code:

        type Person struct {
            Name string
            Age  int
        }
        people := []Person{
            {"Alice", 55},
            {"Bob", 24},
            {"Gopher", 13},
        }
        n, found := slices.BinarySearchFunc(people, Person{"Bob", 0}, func(a, b Person) int {
            return cmp.Compare(a.Name, b.Name)
        })
        fmt.Println("Bob:", n, found)
        

        Output:

        Bob: 1 true
        

        func Clip

        func Clip[S ~[]E, E any](s S) S

        Clip removes unused capacity from the slice, returning s[:len(s):len(s)].

        func Clone

        func Clone[S ~[]E, E any](s S) S

        Clone returns a copy of the slice. The elements are copied using assignment, so this is a shallow clone.

        func Compact

        func Compact[S ~[]E, E comparable](s S) S

        Compact replaces consecutive runs of equal elements with a single copy. This is like the uniq command found on Unix. Compact modifies the contents of the slice s and returns the modified slice, which may have a smaller length. Compact zeroes the elements between the new length and the original length.

        Example

        Code:

        seq := []int{0, 1, 1, 2, 3, 5, 8}
        seq = slices.Compact(seq)
        fmt.Println(seq)
        

        Output:

        [0 1 2 3 5 8]
        

        func CompactFunc

        func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S

        CompactFunc is like Compact but uses an equality function to compare elements. For runs of elements that compare equal, CompactFunc keeps the first one. CompactFunc zeroes the elements between the new length and the original length.

        Example

        Code:

        names := []string{"bob", "Bob", "alice", "Vera", "VERA"}
        names = slices.CompactFunc(names, strings.EqualFold)
        fmt.Println(names)
        

        Output:

        [bob alice Vera]
        

        func Compare

        func Compare[S ~[]E, E cmp.Ordered](s1, s2 S) int

        Compare compares the elements of s1 and s2, using cmp.Compare on each pair of elements. The elements are compared sequentially, starting at index 0, until one element is not equal to the other. The result of comparing the first non-matching elements is returned. If both slices are equal until one of them ends, the shorter slice is considered less than the longer one. The result is 0 if s1 == s2, -1 if s1 < s2, and +1 if s1 > s2.

        Example

        Code:

        names := []string{"Alice", "Bob", "Vera"}
        fmt.Println("Equal:", slices.Compare(names, []string{"Alice", "Bob", "Vera"}))
        fmt.Println("V < X:", slices.Compare(names, []string{"Alice", "Bob", "Xena"}))
        fmt.Println("V > C:", slices.Compare(names, []string{"Alice", "Bob", "Cat"}))
        fmt.Println("3 > 2:", slices.Compare(names, []string{"Alice", "Bob"}))
        

        Output:

        Equal: 0
        V < X: -1
        V > C: 1
        3 > 2: 1
        

        func CompareFunc

        func CompareFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, cmp func(E1, E2) int) int

        CompareFunc is like Compare but uses a custom comparison function on each pair of elements. The result is the first non-zero result of cmp; if cmp always returns 0 the result is 0 if len(s1) == len(s2), -1 if len(s1) < len(s2), and +1 if len(s1) > len(s2).

        Example

        Code:

        numbers := []int{0, 43, 8}
        strings := []string{"0", "0", "8"}
        result := slices.CompareFunc(numbers, strings, func(n int, s string) int {
            sn, err := strconv.Atoi(s)
            if err != nil {
                return 1
            }
            return cmp.Compare(n, sn)
        })
        fmt.Println(result)
        

        Output:

        1
        

        func Concat

        func Concat[S ~[]E, E any](slices ...S) S

        Concat returns a new slice concatenating the passed in slices.

        func Contains

        func Contains[S ~[]E, E comparable](s S, v E) bool

        Contains reports whether v is present in s.

        func ContainsFunc

        func ContainsFunc[S ~[]E, E any](s S, f func(E) bool) bool

        ContainsFunc reports whether at least one element e of s satisfies f(e).

        Example

        Code:

        numbers := []int{0, 42, -10, 8}
        hasNegative := slices.ContainsFunc(numbers, func(n int) bool {
            return n < 0
        })
        fmt.Println("Has a negative:", hasNegative)
        hasOdd := slices.ContainsFunc(numbers, func(n int) bool {
            return n%2 != 0
        })
        fmt.Println("Has an odd number:", hasOdd)
        

        Output:

        Has a negative: true
        Has an odd number: false
        

        func Delete

        func Delete[S ~[]E, E any](s S, i, j int) S

        Delete removes the elements s[i:j] from s, returning the modified slice. Delete panics if j > len(s) or s[i:j] is not a valid slice of s. Delete is O(len(s)-i), so if many items must be deleted, it is better to make a single call deleting them all together than to delete one at a time. Delete zeroes the elements s[len(s)-(j-i):len(s)].

        Example

        Code:

        letters := []string{"a", "b", "c", "d", "e"}
        letters = slices.Delete(letters, 1, 4)
        fmt.Println(letters)
        

        Output:

        [a e]
        

        func DeleteFunc

        func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S

        DeleteFunc removes any elements from s for which del returns true, returning the modified slice. DeleteFunc zeroes the elements between the new length and the original length.

        Example

        Code:

        seq := []int{0, 1, 1, 2, 3, 5, 8}
        seq = slices.DeleteFunc(seq, func(n int) bool {
            return n%2 != 0 // delete the odd numbers
        })
        fmt.Println(seq)
        

        Output:

        [0 2 8]
        

        func Equal

        func Equal[S ~[]E, E comparable](s1, s2 S) bool

        Equal reports whether two slices are equal: the same length and all elements equal. If the lengths are different, Equal returns false. Otherwise, the elements are compared in increasing index order, and the comparison stops at the first unequal pair. Floating point NaNs are not considered equal.

        Example

        Code:

        numbers := []int{0, 42, 8}
        fmt.Println(slices.Equal(numbers, []int{0, 42, 8}))
        fmt.Println(slices.Equal(numbers, []int{10}))
        

        Output:

        true
        false
        

        func EqualFunc

        func EqualFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, eq func(E1, E2) bool) bool

        EqualFunc reports whether two slices are equal using an equality function on each pair of elements. If the lengths are different, EqualFunc returns false. Otherwise, the elements are compared in increasing index order, and the comparison stops at the first index for which eq returns false.

        Example

        Code:

        numbers := []int{0, 42, 8}
        strings := []string{"000", "42", "0o10"}
        equal := slices.EqualFunc(numbers, strings, func(n int, s string) bool {
            sn, err := strconv.ParseInt(s, 0, 64)
            if err != nil {
                return false
            }
            return n == int(sn)
        })
        fmt.Println(equal)
        

        Output:

        true
        

        func Grow

        func Grow[S ~[]E, E any](s S, n int) S

        Grow increases the slice's capacity, if necessary, to guarantee space for another n elements. After Grow(n), at least n elements can be appended to the slice without another allocation. If n is negative or too large to allocate the memory, Grow panics.

        func Index

        func Index[S ~[]E, E comparable](s S, v E) int

        Index returns the index of the first occurrence of v in s, or -1 if not present.

        Example

        Code:

        numbers := []int{0, 42, 8}
        fmt.Println(slices.Index(numbers, 8))
        fmt.Println(slices.Index(numbers, 7))
        

        Output:

        2
        -1
        

        func IndexFunc

        func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int

        IndexFunc returns the first index i satisfying f(s[i]), or -1 if none do.

        Example

        Code:

        numbers := []int{0, 42, -10, 8}
        i := slices.IndexFunc(numbers, func(n int) bool {
            return n < 0
        })
        fmt.Println("First negative at index", i)
        

        Output:

        First negative at index 2
        

        func Insert

        func Insert[S ~[]E, E any](s S, i int, v ...E) S

        Insert inserts the values v... into s at index i, returning the modified slice. The elements at s[i:] are shifted up to make room. In the returned slice r, r[i] == v[0], and r[i+len(v)] == value originally at r[i]. Insert panics if i is out of range. This function is O(len(s) + len(v)).

        Example

        Code:

        names := []string{"Alice", "Bob", "Vera"}
        names = slices.Insert(names, 1, "Bill", "Billie")
        names = slices.Insert(names, len(names), "Zac")
        fmt.Println(names)
        

        Output:

        [Alice Bill Billie Bob Vera Zac]
        

        func IsSorted

        func IsSorted[S ~[]E, E cmp.Ordered](x S) bool

        IsSorted reports whether x is sorted in ascending order.

        Example

        Code:

        fmt.Println(slices.IsSorted([]string{"Alice", "Bob", "Vera"}))
        fmt.Println(slices.IsSorted([]int{0, 2, 1}))
        

        Output:

        true
        false
        

        func IsSortedFunc

        func IsSortedFunc[S ~[]E, E any](x S, cmp func(a, b E) int) bool

        IsSortedFunc reports whether x is sorted in ascending order, with cmp as the comparison function as defined by SortFunc.

        Example

        Code:

        names := []string{"alice", "Bob", "VERA"}
        isSortedInsensitive := slices.IsSortedFunc(names, func(a, b string) int {
            return cmp.Compare(strings.ToLower(a), strings.ToLower(b))
        })
        fmt.Println(isSortedInsensitive)
        fmt.Println(slices.IsSorted(names))
        

        Output:

        true
        false
        

        func Max

        func Max[S ~[]E, E cmp.Ordered](x S) E

        Max returns the maximal value in x. It panics if x is empty. For floating-point E, Max propagates NaNs (any NaN value in x forces the output to be NaN).

        Example

        Code:

        numbers := []int{0, 42, -10, 8}
        fmt.Println(slices.Max(numbers))
        

        Output:

        42
        

        func MaxFunc

        func MaxFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E

        MaxFunc returns the maximal value in x, using cmp to compare elements. It panics if x is empty. If there is more than one maximal element according to the cmp function, MaxFunc returns the first one.

        Example

        Code:

        type Person struct {
            Name string
            Age  int
        }
        people := []Person{
            {"Gopher", 13},
            {"Alice", 55},
            {"Vera", 24},
            {"Bob", 55},
        }
        firstOldest := slices.MaxFunc(people, func(a, b Person) int {
            return cmp.Compare(a.Age, b.Age)
        })
        fmt.Println(firstOldest.Name)
        

        Output:

        Alice
        

        func Min

        func Min[S ~[]E, E cmp.Ordered](x S) E

        Min returns the minimal value in x. It panics if x is empty. For floating-point numbers, Min propagates NaNs (any NaN value in x forces the output to be NaN).

        Example

        Code:

        numbers := []int{0, 42, -10, 8}
        fmt.Println(slices.Min(numbers))
        

        Output:

        -10
        

        func MinFunc

        func MinFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E

        MinFunc returns the minimal value in x, using cmp to compare elements. It panics if x is empty. If there is more than one minimal element according to the cmp function, MinFunc returns the first one.

        Example

        Code:

        type Person struct {
            Name string
            Age  int
        }
        people := []Person{
            {"Gopher", 13},
            {"Bob", 5},
            {"Vera", 24},
            {"Bill", 5},
        }
        firstYoungest := slices.MinFunc(people, func(a, b Person) int {
            return cmp.Compare(a.Age, b.Age)
        })
        fmt.Println(firstYoungest.Name)
        

        Output:

        Bob
        

        func Replace

        func Replace[S ~[]E, E any](s S, i, j int, v ...E) S

        Replace replaces the elements s[i:j] by the given v, and returns the modified slice. Replace panics if j > len(s) or s[i:j] is not a valid slice of s. When len(v) < (j-i), Replace zeroes the elements between the new length and the original length.

        Example

        Code:

        names := []string{"Alice", "Bob", "Vera", "Zac"}
        names = slices.Replace(names, 1, 3, "Bill", "Billie", "Cat")
        fmt.Println(names)
        

        Output:

        [Alice Bill Billie Cat Zac]
        

        func Reverse

        func Reverse[S ~[]E, E any](s S)

        Reverse reverses the elements of the slice in place.

        Example

        Code:

        names := []string{"alice", "Bob", "VERA"}
        slices.Reverse(names)
        fmt.Println(names)
        

        Output:

        [VERA Bob alice]
        

        func Sort

        func Sort[S ~[]E, E cmp.Ordered](x S)

        Sort sorts a slice of any ordered type in ascending order. When sorting floating-point numbers, NaNs are ordered before other values.

        Example

        Code:

        smallInts := []int8{0, 42, -10, 8}
        slices.Sort(smallInts)
        fmt.Println(smallInts)
        

        Output:

        [-10 0 8 42]
        

        func SortFunc

        func SortFunc[S ~[]E, E any](x S, cmp func(a, b E) int)

        SortFunc sorts the slice x in ascending order as determined by the cmp function. This sort is not guaranteed to be stable. cmp(a, b) should return a negative number when a < b, a positive number when a > b and zero when a == b.

        SortFunc requires that cmp is a strict weak ordering. See https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings.

        Example (CaseInsensitive)

        Code:

        names := []string{"Bob", "alice", "VERA"}
        slices.SortFunc(names, func(a, b string) int {
            return cmp.Compare(strings.ToLower(a), strings.ToLower(b))
        })
        fmt.Println(names)
        

        Output:

        [alice Bob VERA]
        

        Example (MultiField)

        Code:

        type Person struct {
            Name string
            Age  int
        }
        people := []Person{
            {"Gopher", 13},
            {"Alice", 55},
            {"Bob", 24},
            {"Alice", 20},
        }
        slices.SortFunc(people, func(a, b Person) int {
            if n := cmp.Compare(a.Name, b.Name); n != 0 {
                return n
            }
            // If names are equal, order by age
            return cmp.Compare(a.Age, b.Age)
        })
        fmt.Println(people)
        

        Output:

        [{Alice 20} {Alice 55} {Bob 24} {Gopher 13}]
        

        func SortStableFunc

        func SortStableFunc[S ~[]E, E any](x S, cmp func(a, b E) int)

        SortStableFunc sorts the slice x while keeping the original order of equal elements, using cmp to compare elements in the same way as SortFunc.

        Example

        Code:

        type Person struct {
            Name string
            Age  int
        }
        people := []Person{
            {"Gopher", 13},
            {"Alice", 20},
            {"Bob", 24},
            {"Alice", 55},
        }
        // Stable sort by name, keeping age ordering of Alices intact
        slices.SortStableFunc(people, func(a, b Person) int {
            return cmp.Compare(a.Name, b.Name)
        })
        fmt.Println(people)
        

        Output:

        [{Alice 20} {Alice 55} {Bob 24} {Gopher 13}]
        
        sort - Go Documentation Server
        ...

        Package sort

        import "sort"
        Overview
        Index
        Examples

        Overview ▾

        Package sort provides primitives for sorting slices and user-defined collections.

        Example

        Code:

        package sort_test
        
        import (
            "fmt"
            "sort"
        )
        
        type Person struct {
            Name string
            Age  int
        }
        
        func (p Person) String() string {
            return fmt.Sprintf("%s: %d", p.Name, p.Age)
        }
        
        // ByAge implements sort.Interface for []Person based on
        // the Age field.
        type ByAge []Person
        
        func (a ByAge) Len() int           { return len(a) }
        func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
        func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
        
        func Example() {
            people := []Person{
                {"Bob", 31},
                {"John", 42},
                {"Michael", 17},
                {"Jenny", 26},
            }
        
            fmt.Println(people)
            // There are two ways to sort a slice. First, one can define
            // a set of methods for the slice type, as with ByAge, and
            // call sort.Sort. In this first example we use that technique.
            sort.Sort(ByAge(people))
            fmt.Println(people)
        
            // The other way is to use sort.Slice with a custom Less
            // function, which can be provided as a closure. In this
            // case no methods are needed. (And if they exist, they
            // are ignored.) Here we re-sort in reverse order: compare
            // the closure with ByAge.Less.
            sort.Slice(people, func(i, j int) bool {
                return people[i].Age > people[j].Age
            })
            fmt.Println(people)
        
            // Output:
            // [Bob: 31 John: 42 Michael: 17 Jenny: 26]
            // [Michael: 17 Jenny: 26 Bob: 31 John: 42]
            // [John: 42 Bob: 31 Jenny: 26 Michael: 17]
        }
        

        Example (SortKeys)

        ExampleSortKeys demonstrates a technique for sorting a struct type using programmable sort criteria.

        Code:

        package sort_test
        
        import (
            "fmt"
            "sort"
        )
        
        // A couple of type definitions to make the units clear.
        type earthMass float64
        type au float64
        
        // A Planet defines the properties of a solar system object.
        type Planet struct {
            name     string
            mass     earthMass
            distance au
        }
        
        // By is the type of a "less" function that defines the ordering of its Planet arguments.
        type By func(p1, p2 *Planet) bool
        
        // Sort is a method on the function type, By, that sorts the argument slice according to the function.
        func (by By) Sort(planets []Planet) {
            ps := &planetSorter{
                planets: planets,
                by:      by, // The Sort method's receiver is the function (closure) that defines the sort order.
            }
            sort.Sort(ps)
        }
        
        // planetSorter joins a By function and a slice of Planets to be sorted.
        type planetSorter struct {
            planets []Planet
            by      func(p1, p2 *Planet) bool // Closure used in the Less method.
        }
        
        // Len is part of sort.Interface.
        func (s *planetSorter) Len() int {
            return len(s.planets)
        }
        
        // Swap is part of sort.Interface.
        func (s *planetSorter) Swap(i, j int) {
            s.planets[i], s.planets[j] = s.planets[j], s.planets[i]
        }
        
        // Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter.
        func (s *planetSorter) Less(i, j int) bool {
            return s.by(&s.planets[i], &s.planets[j])
        }
        
        var planets = []Planet{
            {"Mercury", 0.055, 0.4},
            {"Venus", 0.815, 0.7},
            {"Earth", 1.0, 1.0},
            {"Mars", 0.107, 1.5},
        }
        
        // ExampleSortKeys demonstrates a technique for sorting a struct type using programmable sort criteria.
        func Example_sortKeys() {
            // Closures that order the Planet structure.
            name := func(p1, p2 *Planet) bool {
                return p1.name < p2.name
            }
            mass := func(p1, p2 *Planet) bool {
                return p1.mass < p2.mass
            }
            distance := func(p1, p2 *Planet) bool {
                return p1.distance < p2.distance
            }
            decreasingDistance := func(p1, p2 *Planet) bool {
                return distance(p2, p1)
            }
        
            // Sort the planets by the various criteria.
            By(name).Sort(planets)
            fmt.Println("By name:", planets)
        
            By(mass).Sort(planets)
            fmt.Println("By mass:", planets)
        
            By(distance).Sort(planets)
            fmt.Println("By distance:", planets)
        
            By(decreasingDistance).Sort(planets)
            fmt.Println("By decreasing distance:", planets)
        
            // Output: By name: [{Earth 1 1} {Mars 0.107 1.5} {Mercury 0.055 0.4} {Venus 0.815 0.7}]
            // By mass: [{Mercury 0.055 0.4} {Mars 0.107 1.5} {Venus 0.815 0.7} {Earth 1 1}]
            // By distance: [{Mercury 0.055 0.4} {Venus 0.815 0.7} {Earth 1 1} {Mars 0.107 1.5}]
            // By decreasing distance: [{Mars 0.107 1.5} {Earth 1 1} {Venus 0.815 0.7} {Mercury 0.055 0.4}]
        }
        

        Example (SortMultiKeys)

        ExampleMultiKeys demonstrates a technique for sorting a struct type using different sets of multiple fields in the comparison. We chain together "Less" functions, each of which compares a single field.

        Code:

        package sort_test
        
        import (
            "fmt"
            "sort"
        )
        
        // A Change is a record of source code changes, recording user, language, and delta size.
        type Change struct {
            user     string
            language string
            lines    int
        }
        
        type lessFunc func(p1, p2 *Change) bool
        
        // multiSorter implements the Sort interface, sorting the changes within.
        type multiSorter struct {
            changes []Change
            less    []lessFunc
        }
        
        // Sort sorts the argument slice according to the less functions passed to OrderedBy.
        func (ms *multiSorter) Sort(changes []Change) {
            ms.changes = changes
            sort.Sort(ms)
        }
        
        // OrderedBy returns a Sorter that sorts using the less functions, in order.
        // Call its Sort method to sort the data.
        func OrderedBy(less ...lessFunc) *multiSorter {
            return &multiSorter{
                less: less,
            }
        }
        
        // Len is part of sort.Interface.
        func (ms *multiSorter) Len() int {
            return len(ms.changes)
        }
        
        // Swap is part of sort.Interface.
        func (ms *multiSorter) Swap(i, j int) {
            ms.changes[i], ms.changes[j] = ms.changes[j], ms.changes[i]
        }
        
        // Less is part of sort.Interface. It is implemented by looping along the
        // less functions until it finds a comparison that discriminates between
        // the two items (one is less than the other). Note that it can call the
        // less functions twice per call. We could change the functions to return
        // -1, 0, 1 and reduce the number of calls for greater efficiency: an
        // exercise for the reader.
        func (ms *multiSorter) Less(i, j int) bool {
            p, q := &ms.changes[i], &ms.changes[j]
            // Try all but the last comparison.
            var k int
            for k = 0; k < len(ms.less)-1; k++ {
                less := ms.less[k]
                switch {
                case less(p, q):
                    // p < q, so we have a decision.
                    return true
                case less(q, p):
                    // p > q, so we have a decision.
                    return false
                }
                // p == q; try the next comparison.
            }
            // All comparisons to here said "equal", so just return whatever
            // the final comparison reports.
            return ms.less[k](p, q)
        }
        
        var changes = []Change{
            {"gri", "Go", 100},
            {"ken", "C", 150},
            {"glenda", "Go", 200},
            {"rsc", "Go", 200},
            {"r", "Go", 100},
            {"ken", "Go", 200},
            {"dmr", "C", 100},
            {"r", "C", 150},
            {"gri", "Smalltalk", 80},
        }
        
        // ExampleMultiKeys demonstrates a technique for sorting a struct type using different
        // sets of multiple fields in the comparison. We chain together "Less" functions, each of
        // which compares a single field.
        func Example_sortMultiKeys() {
            // Closures that order the Change structure.
            user := func(c1, c2 *Change) bool {
                return c1.user < c2.user
            }
            language := func(c1, c2 *Change) bool {
                return c1.language < c2.language
            }
            increasingLines := func(c1, c2 *Change) bool {
                return c1.lines < c2.lines
            }
            decreasingLines := func(c1, c2 *Change) bool {
                return c1.lines > c2.lines // Note: > orders downwards.
            }
        
            // Simple use: Sort by user.
            OrderedBy(user).Sort(changes)
            fmt.Println("By user:", changes)
        
            // More examples.
            OrderedBy(user, increasingLines).Sort(changes)
            fmt.Println("By user,<lines:", changes)
        
            OrderedBy(user, decreasingLines).Sort(changes)
            fmt.Println("By user,>lines:", changes)
        
            OrderedBy(language, increasingLines).Sort(changes)
            fmt.Println("By language,<lines:", changes)
        
            OrderedBy(language, increasingLines, user).Sort(changes)
            fmt.Println("By language,<lines,user:", changes)
        
            // Output:
            // By user: [{dmr C 100} {glenda Go 200} {gri Go 100} {gri Smalltalk 80} {ken C 150} {ken Go 200} {r Go 100} {r C 150} {rsc Go 200}]
            // By user,<lines: [{dmr C 100} {glenda Go 200} {gri Smalltalk 80} {gri Go 100} {ken C 150} {ken Go 200} {r Go 100} {r C 150} {rsc Go 200}]
            // By user,>lines: [{dmr C 100} {glenda Go 200} {gri Go 100} {gri Smalltalk 80} {ken Go 200} {ken C 150} {r C 150} {r Go 100} {rsc Go 200}]
            // By language,<lines: [{dmr C 100} {ken C 150} {r C 150} {gri Go 100} {r Go 100} {glenda Go 200} {ken Go 200} {rsc Go 200} {gri Smalltalk 80}]
            // By language,<lines,user: [{dmr C 100} {ken C 150} {r C 150} {gri Go 100} {r Go 100} {glenda Go 200} {ken Go 200} {rsc Go 200} {gri Smalltalk 80}]
        
        }
        

        Example (SortWrapper)

        Code:

        package sort_test
        
        import (
            "fmt"
            "sort"
        )
        
        type Grams int
        
        func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }
        
        type Organ struct {
            Name   string
            Weight Grams
        }
        
        type Organs []*Organ
        
        func (s Organs) Len() int      { return len(s) }
        func (s Organs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
        
        // ByName implements sort.Interface by providing Less and using the Len and
        // Swap methods of the embedded Organs value.
        type ByName struct{ Organs }
        
        func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }
        
        // ByWeight implements sort.Interface by providing Less and using the Len and
        // Swap methods of the embedded Organs value.
        type ByWeight struct{ Organs }
        
        func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < s.Organs[j].Weight }
        
        func Example_sortWrapper() {
            s := []*Organ{
                {"brain", 1340},
                {"heart", 290},
                {"liver", 1494},
                {"pancreas", 131},
                {"prostate", 62},
                {"spleen", 162},
            }
        
            sort.Sort(ByWeight{s})
            fmt.Println("Organs by weight:")
            printOrgans(s)
        
            sort.Sort(ByName{s})
            fmt.Println("Organs by name:")
            printOrgans(s)
        
            // Output:
            // Organs by weight:
            // prostate (62g)
            // pancreas (131g)
            // spleen   (162g)
            // heart    (290g)
            // brain    (1340g)
            // liver    (1494g)
            // Organs by name:
            // brain    (1340g)
            // heart    (290g)
            // liver    (1494g)
            // pancreas (131g)
            // prostate (62g)
            // spleen   (162g)
        }
        
        func printOrgans(s []*Organ) {
            for _, o := range s {
                fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)
            }
        }
        

        Index ▾

        Package files

        search.go slice.go sort.go sort_impl_go121.go zsortfunc.go zsortinterface.go

        func Find

        func Find(n int, cmp func(int) int) (i int, found bool)

        Find uses binary search to find and return the smallest index i in [0, n) at which cmp(i) <= 0. If there is no such index i, Find returns i = n. The found result is true if i < n and cmp(i) == 0. Find calls cmp(i) only for i in the range [0, n).

        To permit binary search, Find requires that cmp(i) > 0 for a leading prefix of the range, cmp(i) == 0 in the middle, and cmp(i) < 0 for the final suffix of the range. (Each subrange could be empty.) The usual way to establish this condition is to interpret cmp(i) as a comparison of a desired target value t against entry i in an underlying indexed data structure x, returning <0, 0, and >0 when t < x[i], t == x[i], and t > x[i], respectively.

        For example, to look for a particular string in a sorted, random-access list of strings:

        i, found := sort.Find(x.Len(), func(i int) int {
            return strings.Compare(target, x.At(i))
        })
        if found {
            fmt.Printf("found %s at entry %d\n", target, i)
        } else {
            fmt.Printf("%s not found, would insert at %d", target, i)
        }
        

        func Float64s

        func Float64s(x []float64)

        Float64s sorts a slice of float64s in increasing order. Not-a-number (NaN) values are ordered before other values.

        Note: as of Go 1.22, this function simply calls slices.Sort.

        Example

        Code:

        s := []float64{5.2, -1.3, 0.7, -3.8, 2.6} // unsorted
        sort.Float64s(s)
        fmt.Println(s)
        
        s = []float64{math.Inf(1), math.NaN(), math.Inf(-1), 0.0} // unsorted
        sort.Float64s(s)
        fmt.Println(s)
        
        

        Output:

        [-3.8 -1.3 0.7 2.6 5.2]
        [NaN -Inf 0 +Inf]
        

        func Float64sAreSorted

        func Float64sAreSorted(x []float64) bool

        Float64sAreSorted reports whether the slice x is sorted in increasing order, with not-a-number (NaN) values before any other values.

        Note: as of Go 1.22, this function simply calls slices.IsSorted.

        Example

        Code:

        s := []float64{0.7, 1.3, 2.6, 3.8, 5.2} // sorted ascending
        fmt.Println(sort.Float64sAreSorted(s))
        
        s = []float64{5.2, 3.8, 2.6, 1.3, 0.7} // sorted descending
        fmt.Println(sort.Float64sAreSorted(s))
        
        s = []float64{5.2, 1.3, 0.7, 3.8, 2.6} // unsorted
        fmt.Println(sort.Float64sAreSorted(s))
        
        

        Output:

        true
        false
        false
        

        func Ints

        func Ints(x []int)

        Ints sorts a slice of ints in increasing order.

        Note: as of Go 1.22, this function simply calls slices.Sort.

        Example

        Code:

        s := []int{5, 2, 6, 3, 1, 4} // unsorted
        sort.Ints(s)
        fmt.Println(s)
        

        Output:

        [1 2 3 4 5 6]
        

        func IntsAreSorted

        func IntsAreSorted(x []int) bool

        IntsAreSorted reports whether the slice x is sorted in increasing order.

        Note: as of Go 1.22, this function simply calls slices.IsSorted.

        Example

        Code:

        s := []int{1, 2, 3, 4, 5, 6} // sorted ascending
        fmt.Println(sort.IntsAreSorted(s))
        
        s = []int{6, 5, 4, 3, 2, 1} // sorted descending
        fmt.Println(sort.IntsAreSorted(s))
        
        s = []int{3, 2, 4, 1, 5} // unsorted
        fmt.Println(sort.IntsAreSorted(s))
        
        

        Output:

        true
        false
        false
        

        func IsSorted

        func IsSorted(data Interface) bool

        IsSorted reports whether data is sorted.

        Note: in many situations, the newer slices.IsSortedFunc function is more ergonomic and runs faster.

        func Search(n int, f func(int) bool) int

        Search uses binary search to find and return the smallest index i in [0, n) at which f(i) is true, assuming that on the range [0, n), f(i) == true implies f(i+1) == true. That is, Search requires that f is false for some (possibly empty) prefix of the input range [0, n) and then true for the (possibly empty) remainder; Search returns the first true index. If there is no such index, Search returns n. (Note that the "not found" return value is not -1 as in, for instance, strings.Index.) Search calls f(i) only for i in the range [0, n).

        A common use of Search is to find the index i for a value x in a sorted, indexable data structure such as an array or slice. In this case, the argument f, typically a closure, captures the value to be searched for, and how the data structure is indexed and ordered.

        For instance, given a slice data sorted in ascending order, the call Search(len(data), func(i int) bool { return data[i] >= 23 }) returns the smallest index i such that data[i] >= 23. If the caller wants to find whether 23 is in the slice, it must test data[i] == 23 separately.

        Searching data sorted in descending order would use the <= operator instead of the >= operator.

        To complete the example above, the following code tries to find the value x in an integer slice data sorted in ascending order:

        x := 23
        i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
        if i < len(data) && data[i] == x {
        	// x is present at data[i]
        } else {
        	// x is not present in data,
        	// but i is the index where it would be inserted.
        }
        

        As a more whimsical example, this program guesses your number:

        func GuessingGame() {
        	var s string
        	fmt.Printf("Pick an integer from 0 to 100.\n")
        	answer := sort.Search(100, func(i int) bool {
        		fmt.Printf("Is your number <= %d? ", i)
        		fmt.Scanf("%s", &s)
        		return s != "" && s[0] == 'y'
        	})
        	fmt.Printf("Your number is %d.\n", answer)
        }
        

        Example (DescendingOrder)

        This example demonstrates searching a list sorted in descending order. The approach is the same as searching a list in ascending order, but with the condition inverted.

        Code:

        a := []int{55, 45, 36, 28, 21, 15, 10, 6, 3, 1}
        x := 6
        
        i := sort.Search(len(a), func(i int) bool { return a[i] <= x })
        if i < len(a) && a[i] == x {
            fmt.Printf("found %d at index %d in %v\n", x, i, a)
        } else {
            fmt.Printf("%d not found in %v\n", x, a)
        }
        

        Output:

        found 6 at index 7 in [55 45 36 28 21 15 10 6 3 1]
        

        func SearchFloat64s

        func SearchFloat64s(a []float64, x float64) int

        SearchFloat64s searches for x in a sorted slice of float64s and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.

        Example

        This example demonstrates searching for float64 in a list sorted in ascending order.

        Code:

        a := []float64{1.0, 2.0, 3.3, 4.6, 6.1, 7.2, 8.0}
        
        x := 2.0
        i := sort.SearchFloat64s(a, x)
        fmt.Printf("found %g at index %d in %v\n", x, i, a)
        
        x = 0.5
        i = sort.SearchFloat64s(a, x)
        fmt.Printf("%g not found, can be inserted at index %d in %v\n", x, i, a)
        

        Output:

        found 2 at index 1 in [1 2 3.3 4.6 6.1 7.2 8]
        0.5 not found, can be inserted at index 0 in [1 2 3.3 4.6 6.1 7.2 8]
        

        func SearchInts

        func SearchInts(a []int, x int) int

        SearchInts searches for x in a sorted slice of ints and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.

        Example

        This example demonstrates searching for int in a list sorted in ascending order.

        Code:

        a := []int{1, 2, 3, 4, 6, 7, 8}
        
        x := 2
        i := sort.SearchInts(a, x)
        fmt.Printf("found %d at index %d in %v\n", x, i, a)
        
        x = 5
        i = sort.SearchInts(a, x)
        fmt.Printf("%d not found, can be inserted at index %d in %v\n", x, i, a)
        

        Output:

        found 2 at index 1 in [1 2 3 4 6 7 8]
        5 not found, can be inserted at index 4 in [1 2 3 4 6 7 8]
        

        func SearchStrings

        func SearchStrings(a []string, x string) int

        SearchStrings searches for x in a sorted slice of strings and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.

        func Slice

        func Slice(x any, less func(i, j int) bool)

        Slice sorts the slice x given the provided less function. It panics if x is not a slice.

        The sort is not guaranteed to be stable: equal elements may be reversed from their original order. For a stable sort, use SliceStable.

        The less function must satisfy the same requirements as the Interface type's Less method.

        Note: in many situations, the newer slices.SortFunc function is more ergonomic and runs faster.

        Example

        Code:

        people := []struct {
            Name string
            Age  int
        }{
            {"Gopher", 7},
            {"Alice", 55},
            {"Vera", 24},
            {"Bob", 75},
        }
        sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
        fmt.Println("By name:", people)
        
        sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
        fmt.Println("By age:", people)
        

        Output:

        By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
        By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]
        

        func SliceIsSorted

        func SliceIsSorted(x any, less func(i, j int) bool) bool

        SliceIsSorted reports whether the slice x is sorted according to the provided less function. It panics if x is not a slice.

        Note: in many situations, the newer slices.IsSortedFunc function is more ergonomic and runs faster.

        func SliceStable

        func SliceStable(x any, less func(i, j int) bool)

        SliceStable sorts the slice x using the provided less function, keeping equal elements in their original order. It panics if x is not a slice.

        The less function must satisfy the same requirements as the Interface type's Less method.

        Note: in many situations, the newer slices.SortStableFunc function is more ergonomic and runs faster.

        Example

        Code:

        people := []struct {
            Name string
            Age  int
        }{
            {"Alice", 25},
            {"Elizabeth", 75},
            {"Alice", 75},
            {"Bob", 75},
            {"Alice", 75},
            {"Bob", 25},
            {"Colin", 25},
            {"Elizabeth", 25},
        }
        
        // Sort by name, preserving original order
        sort.SliceStable(people, func(i, j int) bool { return people[i].Name < people[j].Name })
        fmt.Println("By name:", people)
        
        // Sort by age preserving name order
        sort.SliceStable(people, func(i, j int) bool { return people[i].Age < people[j].Age })
        fmt.Println("By age,name:", people)
        
        

        Output:

        By name: [{Alice 25} {Alice 75} {Alice 75} {Bob 75} {Bob 25} {Colin 25} {Elizabeth 75} {Elizabeth 25}]
        By age,name: [{Alice 25} {Bob 25} {Colin 25} {Elizabeth 25} {Alice 75} {Alice 75} {Bob 75} {Elizabeth 75}]
        

        func Sort

        func Sort(data Interface)

        Sort sorts data in ascending order as determined by the Less method. It makes one call to data.Len to determine n and O(n*log(n)) calls to data.Less and data.Swap. The sort is not guaranteed to be stable.

        Note: in many situations, the newer slices.SortFunc function is more ergonomic and runs faster.

        func Stable

        func Stable(data Interface)

        Stable sorts data in ascending order as determined by the Less method, while keeping the original order of equal elements.

        It makes one call to data.Len to determine n, O(n*log(n)) calls to data.Less and O(n*log(n)*log(n)) calls to data.Swap.

        Note: in many situations, the newer slices.SortStableFunc function is more ergonomic and runs faster.

        func Strings

        func Strings(x []string)

        Strings sorts a slice of strings in increasing order.

        Note: as of Go 1.22, this function simply calls slices.Sort.

        Example

        Code:

        s := []string{"Go", "Bravo", "Gopher", "Alpha", "Grin", "Delta"}
        sort.Strings(s)
        fmt.Println(s)
        

        Output:

        [Alpha Bravo Delta Go Gopher Grin]
        

        func StringsAreSorted

        func StringsAreSorted(x []string) bool

        StringsAreSorted reports whether the slice x is sorted in increasing order.

        Note: as of Go 1.22, this function simply calls slices.IsSorted.

        type Float64Slice

        Float64Slice implements Interface for a []float64, sorting in increasing order, with not-a-number (NaN) values ordered before other values.

        type Float64Slice []float64

        func (Float64Slice) Len

        func (x Float64Slice) Len() int

        func (Float64Slice) Less

        func (x Float64Slice) Less(i, j int) bool

        Less reports whether x[i] should be ordered before x[j], as required by the sort Interface. Note that floating-point comparison by itself is not a transitive relation: it does not report a consistent ordering for not-a-number (NaN) values. This implementation of Less places NaN values before any others, by using:

        x[i] < x[j] || (math.IsNaN(x[i]) && !math.IsNaN(x[j]))
        

        func (Float64Slice) Search

        func (p Float64Slice) Search(x float64) int

        Search returns the result of applying SearchFloat64s to the receiver and x.

        func (Float64Slice) Sort

        func (x Float64Slice) Sort()

        Sort is a convenience method: x.Sort() calls Sort(x).

        func (Float64Slice) Swap

        func (x Float64Slice) Swap(i, j int)

        type IntSlice

        IntSlice attaches the methods of Interface to []int, sorting in increasing order.

        type IntSlice []int

        func (IntSlice) Len

        func (x IntSlice) Len() int

        func (IntSlice) Less

        func (x IntSlice) Less(i, j int) bool

        func (IntSlice) Search

        func (p IntSlice) Search(x int) int

        Search returns the result of applying SearchInts to the receiver and x.

        func (IntSlice) Sort

        func (x IntSlice) Sort()

        Sort is a convenience method: x.Sort() calls Sort(x).

        func (IntSlice) Swap

        func (x IntSlice) Swap(i, j int)

        type Interface

        An implementation of Interface can be sorted by the routines in this package. The methods refer to elements of the underlying collection by integer index.

        type Interface interface {
            // Len is the number of elements in the collection.
            Len() int
        
            // Less reports whether the element with index i
            // must sort before the element with index j.
            //
            // If both Less(i, j) and Less(j, i) are false,
            // then the elements at index i and j are considered equal.
            // Sort may place equal elements in any order in the final result,
            // while Stable preserves the original input order of equal elements.
            //
            // Less must describe a transitive ordering:
            //  - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
            //  - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
            //
            // Note that floating-point comparison (the < operator on float32 or float64 values)
            // is not a transitive ordering when not-a-number (NaN) values are involved.
            // See Float64Slice.Less for a correct implementation for floating-point values.
            Less(i, j int) bool
        
            // Swap swaps the elements with indexes i and j.
            Swap(i, j int)
        }

        func Reverse

        func Reverse(data Interface) Interface

        Reverse returns the reverse order for data.

        Example

        Code:

        s := []int{5, 2, 6, 3, 1, 4} // unsorted
        sort.Sort(sort.Reverse(sort.IntSlice(s)))
        fmt.Println(s)
        

        Output:

        [6 5 4 3 2 1]
        

        type StringSlice

        StringSlice attaches the methods of Interface to []string, sorting in increasing order.

        type StringSlice []string

        func (StringSlice) Len

        func (x StringSlice) Len() int

        func (StringSlice) Less

        func (x StringSlice) Less(i, j int) bool

        func (StringSlice) Search

        func (p StringSlice) Search(x string) int

        Search returns the result of applying SearchStrings to the receiver and x.

        func (StringSlice) Sort

        func (x StringSlice) Sort()

        Sort is a convenience method: x.Sort() calls Sort(x).

        func (StringSlice) Swap

        func (x StringSlice) Swap(i, j int)
        strconv - Go Documentation Server
        ...

        Package strconv

        import "strconv"
        Overview
        Index
        Examples

        Overview ▾

        Package strconv implements conversions to and from string representations of basic data types.

        Numeric Conversions

        The most common numeric conversions are Atoi (string to int) and Itoa (int to string).

        i, err := strconv.Atoi("-42")
        s := strconv.Itoa(-42)
        

        These assume decimal and the Go int type.

        ParseBool, ParseFloat, ParseInt, and ParseUint convert strings to values:

        b, err := strconv.ParseBool("true")
        f, err := strconv.ParseFloat("3.1415", 64)
        i, err := strconv.ParseInt("-42", 10, 64)
        u, err := strconv.ParseUint("42", 10, 64)
        

        The parse functions return the widest type (float64, int64, and uint64), but if the size argument specifies a narrower width the result can be converted to that narrower type without data loss:

        s := "2147483647" // biggest int32
        i64, err := strconv.ParseInt(s, 10, 32)
        ...
        i := int32(i64)
        

        FormatBool, FormatFloat, FormatInt, and FormatUint convert values to strings:

        s := strconv.FormatBool(true)
        s := strconv.FormatFloat(3.1415, 'E', -1, 64)
        s := strconv.FormatInt(-42, 16)
        s := strconv.FormatUint(42, 16)
        

        AppendBool, AppendFloat, AppendInt, and AppendUint are similar but append the formatted value to a destination slice.

        String Conversions

        Quote and QuoteToASCII convert strings to quoted Go string literals. The latter guarantees that the result is an ASCII string, by escaping any non-ASCII Unicode with \u:

        q := strconv.Quote("Hello, 世界")
        q := strconv.QuoteToASCII("Hello, 世界")
        

        QuoteRune and QuoteRuneToASCII are similar but accept runes and return quoted Go rune literals.

        Unquote and UnquoteChar unquote Go string and rune literals.

        Index ▾

        Constants
        Variables
        func AppendBool(dst []byte, b bool) []byte
        func AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte
        func AppendInt(dst []byte, i int64, base int) []byte
        func AppendQuote(dst []byte, s string) []byte
        func AppendQuoteRune(dst []byte, r rune) []byte
        func AppendQuoteRuneToASCII(dst []byte, r rune) []byte
        func AppendQuoteRuneToGraphic(dst []byte, r rune) []byte
        func AppendQuoteToASCII(dst []byte, s string) []byte
        func AppendQuoteToGraphic(dst []byte, s string) []byte
        func AppendUint(dst []byte, i uint64, base int) []byte
        func Atoi(s string) (int, error)
        func CanBackquote(s string) bool
        func FormatBool(b bool) string
        func FormatComplex(c complex128, fmt byte, prec, bitSize int) string
        func FormatFloat(f float64, fmt byte, prec, bitSize int) string
        func FormatInt(i int64, base int) string
        func FormatUint(i uint64, base int) string
        func IsGraphic(r rune) bool
        func IsPrint(r rune) bool
        func Itoa(i int) string
        func ParseBool(str string) (bool, error)
        func ParseComplex(s string, bitSize int) (complex128, error)
        func ParseFloat(s string, bitSize int) (float64, error)
        func ParseInt(s string, base int, bitSize int) (i int64, err error)
        func ParseUint(s string, base int, bitSize int) (uint64, error)
        func Quote(s string) string
        func QuoteRune(r rune) string
        func QuoteRuneToASCII(r rune) string
        func QuoteRuneToGraphic(r rune) string
        func QuoteToASCII(s string) string
        func QuoteToGraphic(s string) string
        func QuotedPrefix(s string) (string, error)
        func Unquote(s string) (string, error)
        func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)
        type NumError
            func (e *NumError) Error() string
            func (e *NumError) Unwrap() error

        Package files

        atob.go atoc.go atof.go atoi.go bytealg.go ctoa.go decimal.go doc.go eisel_lemire.go ftoa.go ftoaryu.go isprint.go itoa.go quote.go

        Constants

        IntSize is the size in bits of an int or uint value.

        const IntSize = intSize

        Variables

        ErrRange indicates that a value is out of range for the target type.

        var ErrRange = errors.New("value out of range")

        ErrSyntax indicates that a value does not have the right syntax for the target type.

        var ErrSyntax = errors.New("invalid syntax")

        func AppendBool

        func AppendBool(dst []byte, b bool) []byte

        AppendBool appends "true" or "false", according to the value of b, to dst and returns the extended buffer.

        Example

        Code:

        b := []byte("bool:")
        b = strconv.AppendBool(b, true)
        fmt.Println(string(b))
        
        

        Output:

        bool:true
        

        func AppendFloat

        func AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte

        AppendFloat appends the string form of the floating-point number f, as generated by FormatFloat, to dst and returns the extended buffer.

        Example

        Code:

        b32 := []byte("float32:")
        b32 = strconv.AppendFloat(b32, 3.1415926535, 'E', -1, 32)
        fmt.Println(string(b32))
        
        b64 := []byte("float64:")
        b64 = strconv.AppendFloat(b64, 3.1415926535, 'E', -1, 64)
        fmt.Println(string(b64))
        
        

        Output:

        float32:3.1415927E+00
        float64:3.1415926535E+00
        

        func AppendInt

        func AppendInt(dst []byte, i int64, base int) []byte

        AppendInt appends the string form of the integer i, as generated by FormatInt, to dst and returns the extended buffer.

        Example

        Code:

        b10 := []byte("int (base 10):")
        b10 = strconv.AppendInt(b10, -42, 10)
        fmt.Println(string(b10))
        
        b16 := []byte("int (base 16):")
        b16 = strconv.AppendInt(b16, -42, 16)
        fmt.Println(string(b16))
        
        

        Output:

        int (base 10):-42
        int (base 16):-2a
        

        func AppendQuote

        func AppendQuote(dst []byte, s string) []byte

        AppendQuote appends a double-quoted Go string literal representing s, as generated by Quote, to dst and returns the extended buffer.

        Example

        Code:

        b := []byte("quote:")
        b = strconv.AppendQuote(b, `"Fran & Freddie's Diner"`)
        fmt.Println(string(b))
        
        

        Output:

        quote:"\"Fran & Freddie's Diner\""
        

        func AppendQuoteRune

        func AppendQuoteRune(dst []byte, r rune) []byte

        AppendQuoteRune appends a single-quoted Go character literal representing the rune, as generated by QuoteRune, to dst and returns the extended buffer.

        Example

        Code:

        b := []byte("rune:")
        b = strconv.AppendQuoteRune(b, '☺')
        fmt.Println(string(b))
        
        

        Output:

        rune:'☺'
        

        func AppendQuoteRuneToASCII

        func AppendQuoteRuneToASCII(dst []byte, r rune) []byte

        AppendQuoteRuneToASCII appends a single-quoted Go character literal representing the rune, as generated by QuoteRuneToASCII, to dst and returns the extended buffer.

        Example

        Code:

        b := []byte("rune (ascii):")
        b = strconv.AppendQuoteRuneToASCII(b, '☺')
        fmt.Println(string(b))
        
        

        Output:

        rune (ascii):'\u263a'
        

        func AppendQuoteRuneToGraphic

        func AppendQuoteRuneToGraphic(dst []byte, r rune) []byte

        AppendQuoteRuneToGraphic appends a single-quoted Go character literal representing the rune, as generated by QuoteRuneToGraphic, to dst and returns the extended buffer.

        func AppendQuoteToASCII

        func AppendQuoteToASCII(dst []byte, s string) []byte

        AppendQuoteToASCII appends a double-quoted Go string literal representing s, as generated by QuoteToASCII, to dst and returns the extended buffer.

        Example

        Code:

        b := []byte("quote (ascii):")
        b = strconv.AppendQuoteToASCII(b, `"Fran & Freddie's Diner"`)
        fmt.Println(string(b))
        
        

        Output:

        quote (ascii):"\"Fran & Freddie's Diner\""
        

        func AppendQuoteToGraphic

        func AppendQuoteToGraphic(dst []byte, s string) []byte

        AppendQuoteToGraphic appends a double-quoted Go string literal representing s, as generated by QuoteToGraphic, to dst and returns the extended buffer.

        func AppendUint

        func AppendUint(dst []byte, i uint64, base int) []byte

        AppendUint appends the string form of the unsigned integer i, as generated by FormatUint, to dst and returns the extended buffer.

        Example

        Code:

        b10 := []byte("uint (base 10):")
        b10 = strconv.AppendUint(b10, 42, 10)
        fmt.Println(string(b10))
        
        b16 := []byte("uint (base 16):")
        b16 = strconv.AppendUint(b16, 42, 16)
        fmt.Println(string(b16))
        
        

        Output:

        uint (base 10):42
        uint (base 16):2a
        

        func Atoi

        func Atoi(s string) (int, error)

        Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.

        Example

        Code:

        v := "10"
        if s, err := strconv.Atoi(v); err == nil {
            fmt.Printf("%T, %v", s, s)
        }
        
        

        Output:

        int, 10
        

        func CanBackquote

        func CanBackquote(s string) bool

        CanBackquote reports whether the string s can be represented unchanged as a single-line backquoted string without control characters other than tab.

        Example

        Code:

        fmt.Println(strconv.CanBackquote("Fran & Freddie's Diner ☺"))
        fmt.Println(strconv.CanBackquote("`can't backquote this`"))
        
        

        Output:

        true
        false
        

        func FormatBool

        func FormatBool(b bool) string

        FormatBool returns "true" or "false" according to the value of b.

        Example

        Code:

        v := true
        s := strconv.FormatBool(v)
        fmt.Printf("%T, %v\n", s, s)
        
        

        Output:

        string, true
        

        func FormatComplex

        func FormatComplex(c complex128, fmt byte, prec, bitSize int) string

        FormatComplex converts the complex number c to a string of the form (a+bi) where a and b are the real and imaginary parts, formatted according to the format fmt and precision prec.

        The format fmt and precision prec have the same meaning as in FormatFloat. It rounds the result assuming that the original was obtained from a complex value of bitSize bits, which must be 64 for complex64 and 128 for complex128.

        func FormatFloat

        func FormatFloat(f float64, fmt byte, prec, bitSize int) string

        FormatFloat converts the floating-point number f to a string, according to the format fmt and precision prec. It rounds the result assuming that the original was obtained from a floating-point value of bitSize bits (32 for float32, 64 for float64).

        The format fmt is one of 'b' (-ddddp±ddd, a binary exponent), 'e' (-d.dddde±dd, a decimal exponent), 'E' (-d.ddddE±dd, a decimal exponent), 'f' (-ddd.dddd, no exponent), 'g' ('e' for large exponents, 'f' otherwise), 'G' ('E' for large exponents, 'f' otherwise), 'x' (-0xd.ddddp±ddd, a hexadecimal fraction and binary exponent), or 'X' (-0Xd.ddddP±ddd, a hexadecimal fraction and binary exponent).

        The precision prec controls the number of digits (excluding the exponent) printed by the 'e', 'E', 'f', 'g', 'G', 'x', and 'X' formats. For 'e', 'E', 'f', 'x', and 'X', it is the number of digits after the decimal point. For 'g' and 'G' it is the maximum number of significant digits (trailing zeros are removed). The special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly.

        Example

        Code:

        v := 3.1415926535
        
        s32 := strconv.FormatFloat(v, 'E', -1, 32)
        fmt.Printf("%T, %v\n", s32, s32)
        
        s64 := strconv.FormatFloat(v, 'E', -1, 64)
        fmt.Printf("%T, %v\n", s64, s64)
        
        // fmt.Println uses these arguments to print floats
        fmt64 := strconv.FormatFloat(v, 'g', -1, 64)
        fmt.Printf("%T, %v\n", fmt64, fmt64)
        
        

        Output:

        string, 3.1415927E+00
        string, 3.1415926535E+00
        string, 3.1415926535
        

        func FormatInt

        func FormatInt(i int64, base int) string

        FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.

        Example

        Code:

        v := int64(-42)
        
        s10 := strconv.FormatInt(v, 10)
        fmt.Printf("%T, %v\n", s10, s10)
        
        s16 := strconv.FormatInt(v, 16)
        fmt.Printf("%T, %v\n", s16, s16)
        
        

        Output:

        string, -42
        string, -2a
        

        func FormatUint

        func FormatUint(i uint64, base int) string

        FormatUint returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.

        Example

        Code:

        v := uint64(42)
        
        s10 := strconv.FormatUint(v, 10)
        fmt.Printf("%T, %v\n", s10, s10)
        
        s16 := strconv.FormatUint(v, 16)
        fmt.Printf("%T, %v\n", s16, s16)
        
        

        Output:

        string, 42
        string, 2a
        

        func IsGraphic

        func IsGraphic(r rune) bool

        IsGraphic reports whether the rune is defined as a Graphic by Unicode. Such characters include letters, marks, numbers, punctuation, symbols, and spaces, from categories L, M, N, P, S, and Zs.

        Example

        Code:

        shamrock := strconv.IsGraphic('☘')
        fmt.Println(shamrock)
        
        a := strconv.IsGraphic('a')
        fmt.Println(a)
        
        bel := strconv.IsGraphic('\007')
        fmt.Println(bel)
        
        

        Output:

        true
        true
        false
        

        func IsPrint

        func IsPrint(r rune) bool

        IsPrint reports whether the rune is defined as printable by Go, with the same definition as unicode.IsPrint: letters, numbers, punctuation, symbols and ASCII space.

        Example

        Code:

        c := strconv.IsPrint('\u263a')
        fmt.Println(c)
        
        bel := strconv.IsPrint('\007')
        fmt.Println(bel)
        
        

        Output:

        true
        false
        

        func Itoa

        func Itoa(i int) string

        Itoa is equivalent to FormatInt(int64(i), 10).

        Example

        Code:

        i := 10
        s := strconv.Itoa(i)
        fmt.Printf("%T, %v\n", s, s)
        
        

        Output:

        string, 10
        

        func ParseBool

        func ParseBool(str string) (bool, error)

        ParseBool returns the boolean value represented by the string. It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other value returns an error.

        Example

        Code:

        v := "true"
        if s, err := strconv.ParseBool(v); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        
        

        Output:

        bool, true
        

        func ParseComplex

        func ParseComplex(s string, bitSize int) (complex128, error)

        ParseComplex converts the string s to a complex number with the precision specified by bitSize: 64 for complex64, or 128 for complex128. When bitSize=64, the result still has type complex128, but it will be convertible to complex64 without changing its value.

        The number represented by s must be of the form N, Ni, or N±Ni, where N stands for a floating-point number as recognized by ParseFloat, and i is the imaginary component. If the second N is unsigned, a + sign is required between the two components as indicated by the ±. If the second N is NaN, only a + sign is accepted. The form may be parenthesized and cannot contain any spaces. The resulting complex number consists of the two components converted by ParseFloat.

        The errors that ParseComplex returns have concrete type *NumError and include err.Num = s.

        If s is not syntactically well-formed, ParseComplex returns err.Err = ErrSyntax.

        If s is syntactically well-formed but either component is more than 1/2 ULP away from the largest floating point number of the given component's size, ParseComplex returns err.Err = ErrRange and c = ±Inf for the respective component.

        func ParseFloat

        func ParseFloat(s string, bitSize int) (float64, error)

        ParseFloat converts the string s to a floating-point number with the precision specified by bitSize: 32 for float32, or 64 for float64. When bitSize=32, the result still has type float64, but it will be convertible to float32 without changing its value.

        ParseFloat accepts decimal and hexadecimal floating-point numbers as defined by the Go syntax for floating-point literals. If s is well-formed and near a valid floating-point number, ParseFloat returns the nearest floating-point number rounded using IEEE754 unbiased rounding. (Parsing a hexadecimal floating-point value only rounds when there are more bits in the hexadecimal representation than will fit in the mantissa.)

        The errors that ParseFloat returns have concrete type *NumError and include err.Num = s.

        If s is not syntactically well-formed, ParseFloat returns err.Err = ErrSyntax.

        If s is syntactically well-formed but is more than 1/2 ULP away from the largest floating point number of the given size, ParseFloat returns f = ±Inf, err.Err = ErrRange.

        ParseFloat recognizes the string "NaN", and the (possibly signed) strings "Inf" and "Infinity" as their respective special floating point values. It ignores case when matching.

        Example

        Code:

        v := "3.1415926535"
        if s, err := strconv.ParseFloat(v, 32); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        if s, err := strconv.ParseFloat(v, 64); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        if s, err := strconv.ParseFloat("NaN", 32); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        // ParseFloat is case insensitive
        if s, err := strconv.ParseFloat("nan", 32); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        if s, err := strconv.ParseFloat("inf", 32); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        if s, err := strconv.ParseFloat("+Inf", 32); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        if s, err := strconv.ParseFloat("-Inf", 32); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        if s, err := strconv.ParseFloat("-0", 32); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        if s, err := strconv.ParseFloat("+0", 32); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        
        

        Output:

        float64, 3.1415927410125732
        float64, 3.1415926535
        float64, NaN
        float64, NaN
        float64, +Inf
        float64, +Inf
        float64, -Inf
        float64, -0
        float64, 0
        

        func ParseInt

        func ParseInt(s string, base int, bitSize int) (i int64, err error)

        ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.

        The string may begin with a leading sign: "+" or "-".

        If the base argument is 0, the true base is implied by the string's prefix following the sign (if present): 2 for "0b", 8 for "0" or "0o", 16 for "0x", and 10 otherwise. Also, for argument base 0 only, underscore characters are permitted as defined by the Go syntax for integer literals.

        The bitSize argument specifies the integer type that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64. If bitSize is below 0 or above 64, an error is returned.

        The errors that ParseInt returns have concrete type *NumError and include err.Num = s. If s is empty or contains invalid digits, err.Err = ErrSyntax and the returned value is 0; if the value corresponding to s cannot be represented by a signed integer of the given size, err.Err = ErrRange and the returned value is the maximum magnitude integer of the appropriate bitSize and sign.

        Example

        Code:

        v32 := "-354634382"
        if s, err := strconv.ParseInt(v32, 10, 32); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        if s, err := strconv.ParseInt(v32, 16, 32); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        
        v64 := "-3546343826724305832"
        if s, err := strconv.ParseInt(v64, 10, 64); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        if s, err := strconv.ParseInt(v64, 16, 64); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        
        

        Output:

        int64, -354634382
        int64, -3546343826724305832
        

        func ParseUint

        func ParseUint(s string, base int, bitSize int) (uint64, error)

        ParseUint is like ParseInt but for unsigned numbers.

        A sign prefix is not permitted.

        Example

        Code:

        v := "42"
        if s, err := strconv.ParseUint(v, 10, 32); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        if s, err := strconv.ParseUint(v, 10, 64); err == nil {
            fmt.Printf("%T, %v\n", s, s)
        }
        
        

        Output:

        uint64, 42
        uint64, 42
        

        func Quote

        func Quote(s string) string

        Quote returns a double-quoted Go string literal representing s. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for control characters and non-printable characters as defined by IsPrint.

        Example

        Code:

        // This string literal contains a tab character.
        s := strconv.Quote(`"Fran & Freddie's Diner	☺"`)
        fmt.Println(s)
        
        

        Output:

        "\"Fran & Freddie's Diner\t☺\""
        

        func QuoteRune

        func QuoteRune(r rune) string

        QuoteRune returns a single-quoted Go character literal representing the rune. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for control characters and non-printable characters as defined by IsPrint. If r is not a valid Unicode code point, it is interpreted as the Unicode replacement character U+FFFD.

        Example

        Code:

        s := strconv.QuoteRune('☺')
        fmt.Println(s)
        
        

        Output:

        '☺'
        

        func QuoteRuneToASCII

        func QuoteRuneToASCII(r rune) string

        QuoteRuneToASCII returns a single-quoted Go character literal representing the rune. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for non-ASCII characters and non-printable characters as defined by IsPrint. If r is not a valid Unicode code point, it is interpreted as the Unicode replacement character U+FFFD.

        Example

        Code:

        s := strconv.QuoteRuneToASCII('☺')
        fmt.Println(s)
        
        

        Output:

        '\u263a'
        

        func QuoteRuneToGraphic

        func QuoteRuneToGraphic(r rune) string

        QuoteRuneToGraphic returns a single-quoted Go character literal representing the rune. If the rune is not a Unicode graphic character, as defined by IsGraphic, the returned string will use a Go escape sequence (\t, \n, \xFF, \u0100). If r is not a valid Unicode code point, it is interpreted as the Unicode replacement character U+FFFD.

        Example

        Code:

        s := strconv.QuoteRuneToGraphic('☺')
        fmt.Println(s)
        
        s = strconv.QuoteRuneToGraphic('\u263a')
        fmt.Println(s)
        
        s = strconv.QuoteRuneToGraphic('\u000a')
        fmt.Println(s)
        
        s = strconv.QuoteRuneToGraphic('	') // tab character
        fmt.Println(s)
        
        

        Output:

        '☺'
        '☺'
        '\n'
        '\t'
        

        func QuoteToASCII

        func QuoteToASCII(s string) string

        QuoteToASCII returns a double-quoted Go string literal representing s. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for non-ASCII characters and non-printable characters as defined by IsPrint.

        Example

        Code:

        // This string literal contains a tab character.
        s := strconv.QuoteToASCII(`"Fran & Freddie's Diner	☺"`)
        fmt.Println(s)
        
        

        Output:

        "\"Fran & Freddie's Diner\t\u263a\""
        

        func QuoteToGraphic

        func QuoteToGraphic(s string) string

        QuoteToGraphic returns a double-quoted Go string literal representing s. The returned string leaves Unicode graphic characters, as defined by IsGraphic, unchanged and uses Go escape sequences (\t, \n, \xFF, \u0100) for non-graphic characters.

        Example

        Code:

        s := strconv.QuoteToGraphic("☺")
        fmt.Println(s)
        
        // This string literal contains a tab character.
        s = strconv.QuoteToGraphic("This is a \u263a	\u000a")
        fmt.Println(s)
        
        s = strconv.QuoteToGraphic(`" This is a ☺ \n "`)
        fmt.Println(s)
        
        

        Output:

        "☺"
        "This is a ☺\t\n"
        "\" This is a ☺ \\n \""
        

        func QuotedPrefix

        func QuotedPrefix(s string) (string, error)

        QuotedPrefix returns the quoted string (as understood by Unquote) at the prefix of s. If s does not start with a valid quoted string, QuotedPrefix returns an error.

        Example

        Code:

        s, err := strconv.QuotedPrefix("not a quoted string")
        fmt.Printf("%q, %v\n", s, err)
        s, err = strconv.QuotedPrefix("\"double-quoted string\" with trailing text")
        fmt.Printf("%q, %v\n", s, err)
        s, err = strconv.QuotedPrefix("`or backquoted` with more trailing text")
        fmt.Printf("%q, %v\n", s, err)
        s, err = strconv.QuotedPrefix("'\u263a' is also okay")
        fmt.Printf("%q, %v\n", s, err)
        
        

        Output:

        "", invalid syntax
        "\"double-quoted string\"", <nil>
        "`or backquoted`", <nil>
        "'☺'", <nil>
        

        func Unquote

        func Unquote(s string) (string, error)

        Unquote interprets s as a single-quoted, double-quoted, or backquoted Go string literal, returning the string value that s quotes. (If s is single-quoted, it would be a Go character literal; Unquote returns the corresponding one-character string.)

        Example

        Code:

        s, err := strconv.Unquote("You can't unquote a string without quotes")
        fmt.Printf("%q, %v\n", s, err)
        s, err = strconv.Unquote("\"The string must be either double-quoted\"")
        fmt.Printf("%q, %v\n", s, err)
        s, err = strconv.Unquote("`or backquoted.`")
        fmt.Printf("%q, %v\n", s, err)
        s, err = strconv.Unquote("'\u263a'") // single character only allowed in single quotes
        fmt.Printf("%q, %v\n", s, err)
        s, err = strconv.Unquote("'\u2639\u2639'")
        fmt.Printf("%q, %v\n", s, err)
        
        

        Output:

        "", invalid syntax
        "The string must be either double-quoted", <nil>
        "or backquoted.", <nil>
        "☺", <nil>
        "", invalid syntax
        

        func UnquoteChar

        func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)

        UnquoteChar decodes the first character or byte in the escaped string or character literal represented by the string s. It returns four values:

        1. value, the decoded Unicode code point or byte value;
        2. multibyte, a boolean indicating whether the decoded character requires a multibyte UTF-8 representation;
        3. tail, the remainder of the string after the character; and
        4. an error that will be nil if the character is syntactically valid.

        The second argument, quote, specifies the type of literal being parsed and therefore which escaped quote character is permitted. If set to a single quote, it permits the sequence \' and disallows unescaped '. If set to a double quote, it permits \" and disallows unescaped ". If set to zero, it does not permit either escape and allows both quote characters to appear unescaped.

        Example

        Code:

        v, mb, t, err := strconv.UnquoteChar(`\"Fran & Freddie's Diner\"`, '"')
        if err != nil {
            log.Fatal(err)
        }
        
        fmt.Println("value:", string(v))
        fmt.Println("multibyte:", mb)
        fmt.Println("tail:", t)
        
        

        Output:

        value: "
        multibyte: false
        tail: Fran & Freddie's Diner\"
        

        type NumError

        A NumError records a failed conversion.

        type NumError struct {
            Func string // the failing function (ParseBool, ParseInt, ParseUint, ParseFloat, ParseComplex)
            Num  string // the input
            Err  error  // the reason the conversion failed (e.g. ErrRange, ErrSyntax, etc.)
        }
        

        Example

        Code:

        str := "Not a number"
        if _, err := strconv.ParseFloat(str, 64); err != nil {
            e := err.(*strconv.NumError)
            fmt.Println("Func:", e.Func)
            fmt.Println("Num:", e.Num)
            fmt.Println("Err:", e.Err)
            fmt.Println(err)
        }
        
        

        Output:

        Func: ParseFloat
        Num: Not a number
        Err: invalid syntax
        strconv.ParseFloat: parsing "Not a number": invalid syntax
        

        func (*NumError) Error

        func (e *NumError) Error() string

        func (*NumError) Unwrap

        func (e *NumError) Unwrap() error
        strings - Go Documentation Server
        ...

        Package strings

        import "strings"
        Overview
        Index
        Examples

        Overview ▾

        Package strings implements simple functions to manipulate UTF-8 encoded strings.

        For information about UTF-8 strings in Go, see https://blog.golang.org/strings.

        Index ▾

        func Clone(s string) string
        func Compare(a, b string) int
        func Contains(s, substr string) bool
        func ContainsAny(s, chars string) bool
        func ContainsFunc(s string, f func(rune) bool) bool
        func ContainsRune(s string, r rune) bool
        func Count(s, substr string) int
        func Cut(s, sep string) (before, after string, found bool)
        func CutPrefix(s, prefix string) (after string, found bool)
        func CutSuffix(s, suffix string) (before string, found bool)
        func EqualFold(s, t string) bool
        func Fields(s string) []string
        func FieldsFunc(s string, f func(rune) bool) []string
        func HasPrefix(s, prefix string) bool
        func HasSuffix(s, suffix string) bool
        func Index(s, substr string) int
        func IndexAny(s, chars string) int
        func IndexByte(s string, c byte) int
        func IndexFunc(s string, f func(rune) bool) int
        func IndexRune(s string, r rune) int
        func Join(elems []string, sep string) string
        func LastIndex(s, substr string) int
        func LastIndexAny(s, chars string) int
        func LastIndexByte(s string, c byte) int
        func LastIndexFunc(s string, f func(rune) bool) int
        func Map(mapping func(rune) rune, s string) string
        func Repeat(s string, count int) string
        func Replace(s, old, new string, n int) string
        func ReplaceAll(s, old, new string) string
        func Split(s, sep string) []string
        func SplitAfter(s, sep string) []string
        func SplitAfterN(s, sep string, n int) []string
        func SplitN(s, sep string, n int) []string
        func Title(s string) string
        func ToLower(s string) string
        func ToLowerSpecial(c unicode.SpecialCase, s string) string
        func ToTitle(s string) string
        func ToTitleSpecial(c unicode.SpecialCase, s string) string
        func ToUpper(s string) string
        func ToUpperSpecial(c unicode.SpecialCase, s string) string
        func ToValidUTF8(s, replacement string) string
        func Trim(s, cutset string) string
        func TrimFunc(s string, f func(rune) bool) string
        func TrimLeft(s, cutset string) string
        func TrimLeftFunc(s string, f func(rune) bool) string
        func TrimPrefix(s, prefix string) string
        func TrimRight(s, cutset string) string
        func TrimRightFunc(s string, f func(rune) bool) string
        func TrimSpace(s string) string
        func TrimSuffix(s, suffix string) string
        type Builder
            func (b *Builder) Cap() int
            func (b *Builder) Grow(n int)
            func (b *Builder) Len() int
            func (b *Builder) Reset()
            func (b *Builder) String() string
            func (b *Builder) Write(p []byte) (int, error)
            func (b *Builder) WriteByte(c byte) error
            func (b *Builder) WriteRune(r rune) (int, error)
            func (b *Builder) WriteString(s string) (int, error)
        type Reader
            func NewReader(s string) *Reader
            func (r *Reader) Len() int
            func (r *Reader) Read(b []byte) (n int, err error)
            func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)
            func (r *Reader) ReadByte() (byte, error)
            func (r *Reader) ReadRune() (ch rune, size int, err error)
            func (r *Reader) Reset(s string)
            func (r *Reader) Seek(offset int64, whence int) (int64, error)
            func (r *Reader) Size() int64
            func (r *Reader) UnreadByte() error
            func (r *Reader) UnreadRune() error
            func (r *Reader) WriteTo(w io.Writer) (n int64, err error)
        type Replacer
            func NewReplacer(oldnew ...string) *Replacer
            func (r *Replacer) Replace(s string) string
            func (r *Replacer) WriteString(w io.Writer, s string) (n int, err error)

        Package files

        builder.go clone.go compare.go reader.go replace.go search.go strings.go

        func Clone

        func Clone(s string) string

        Clone returns a fresh copy of s. It guarantees to make a copy of s into a new allocation, which can be important when retaining only a small substring of a much larger string. Using Clone can help such programs use less memory. Of course, since using Clone makes a copy, overuse of Clone can make programs use more memory. Clone should typically be used only rarely, and only when profiling indicates that it is needed. For strings of length zero the string "" will be returned and no allocation is made.

        Example

        Code:

        s := "abc"
        clone := strings.Clone(s)
        fmt.Println(s == clone)
        fmt.Println(unsafe.StringData(s) == unsafe.StringData(clone))
        

        Output:

        true
        false
        

        func Compare

        func Compare(a, b string) int

        Compare returns an integer comparing two strings lexicographically. The result will be 0 if a == b, -1 if a < b, and +1 if a > b.

        Compare is included only for symmetry with package bytes. It is usually clearer and always faster to use the built-in string comparison operators ==, <, >, and so on.

        Example

        Code:

        fmt.Println(strings.Compare("a", "b"))
        fmt.Println(strings.Compare("a", "a"))
        fmt.Println(strings.Compare("b", "a"))
        

        Output:

        -1
        0
        1
        

        func Contains

        func Contains(s, substr string) bool

        Contains reports whether substr is within s.

        Example

        Code:

        fmt.Println(strings.Contains("seafood", "foo"))
        fmt.Println(strings.Contains("seafood", "bar"))
        fmt.Println(strings.Contains("seafood", ""))
        fmt.Println(strings.Contains("", ""))
        

        Output:

        true
        false
        true
        true
        

        func ContainsAny

        func ContainsAny(s, chars string) bool

        ContainsAny reports whether any Unicode code points in chars are within s.

        Example

        Code:

        fmt.Println(strings.ContainsAny("team", "i"))
        fmt.Println(strings.ContainsAny("fail", "ui"))
        fmt.Println(strings.ContainsAny("ure", "ui"))
        fmt.Println(strings.ContainsAny("failure", "ui"))
        fmt.Println(strings.ContainsAny("foo", ""))
        fmt.Println(strings.ContainsAny("", ""))
        

        Output:

        false
        true
        true
        true
        false
        false
        

        func ContainsFunc

        func ContainsFunc(s string, f func(rune) bool) bool

        ContainsFunc reports whether any Unicode code points r within s satisfy f(r).

        Example

        Code:

        f := func(r rune) bool {
            return r == 'a' || r == 'e' || r == 'i' || r == 'o' || r == 'u'
        }
        fmt.Println(strings.ContainsFunc("hello", f))
        fmt.Println(strings.ContainsFunc("rhythms", f))
        

        Output:

        true
        false
        

        func ContainsRune

        func ContainsRune(s string, r rune) bool

        ContainsRune reports whether the Unicode code point r is within s.

        Example

        Code:

        // Finds whether a string contains a particular Unicode code point.
        // The code point for the lowercase letter "a", for example, is 97.
        fmt.Println(strings.ContainsRune("aardvark", 97))
        fmt.Println(strings.ContainsRune("timeout", 97))
        

        Output:

        true
        false
        

        func Count

        func Count(s, substr string) int

        Count counts the number of non-overlapping instances of substr in s. If substr is an empty string, Count returns 1 + the number of Unicode code points in s.

        Example

        Code:

        fmt.Println(strings.Count("cheese", "e"))
        fmt.Println(strings.Count("five", "")) // before & after each rune
        

        Output:

        3
        5
        

        func Cut

        func Cut(s, sep string) (before, after string, found bool)

        Cut slices s around the first instance of sep, returning the text before and after sep. The found result reports whether sep appears in s. If sep does not appear in s, cut returns s, "", false.

        Example

        Code:

        show := func(s, sep string) {
            before, after, found := strings.Cut(s, sep)
            fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
        }
        show("Gopher", "Go")
        show("Gopher", "ph")
        show("Gopher", "er")
        show("Gopher", "Badger")
        

        Output:

        Cut("Gopher", "Go") = "", "pher", true
        Cut("Gopher", "ph") = "Go", "er", true
        Cut("Gopher", "er") = "Goph", "", true
        Cut("Gopher", "Badger") = "Gopher", "", false
        

        func CutPrefix

        func CutPrefix(s, prefix string) (after string, found bool)

        CutPrefix returns s without the provided leading prefix string and reports whether it found the prefix. If s doesn't start with prefix, CutPrefix returns s, false. If prefix is the empty string, CutPrefix returns s, true.

        Example

        Code:

        show := func(s, sep string) {
            after, found := strings.CutPrefix(s, sep)
            fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, sep, after, found)
        }
        show("Gopher", "Go")
        show("Gopher", "ph")
        

        Output:

        CutPrefix("Gopher", "Go") = "pher", true
        CutPrefix("Gopher", "ph") = "Gopher", false
        

        func CutSuffix

        func CutSuffix(s, suffix string) (before string, found bool)

        CutSuffix returns s without the provided ending suffix string and reports whether it found the suffix. If s doesn't end with suffix, CutSuffix returns s, false. If suffix is the empty string, CutSuffix returns s, true.

        Example

        Code:

        show := func(s, sep string) {
            before, found := strings.CutSuffix(s, sep)
            fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, sep, before, found)
        }
        show("Gopher", "Go")
        show("Gopher", "er")
        

        Output:

        CutSuffix("Gopher", "Go") = "Gopher", false
        CutSuffix("Gopher", "er") = "Goph", true
        

        func EqualFold

        func EqualFold(s, t string) bool

        EqualFold reports whether s and t, interpreted as UTF-8 strings, are equal under simple Unicode case-folding, which is a more general form of case-insensitivity.

        Example

        Code:

        fmt.Println(strings.EqualFold("Go", "go"))
        fmt.Println(strings.EqualFold("AB", "ab")) // true because comparison uses simple case-folding
        fmt.Println(strings.EqualFold("ß", "ss"))  // false because comparison does not use full case-folding
        

        Output:

        true
        true
        false
        

        func Fields

        func Fields(s string) []string

        Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space.

        Example

        Code:

        fmt.Printf("Fields are: %q", strings.Fields("  foo bar  baz   "))
        

        Output:

        Fields are: ["foo" "bar" "baz"]
        

        func FieldsFunc

        func FieldsFunc(s string, f func(rune) bool) []string

        FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c) and returns an array of slices of s. If all code points in s satisfy f(c) or the string is empty, an empty slice is returned.

        FieldsFunc makes no guarantees about the order in which it calls f(c) and assumes that f always returns the same value for a given c.

        Example

        Code:

        f := func(c rune) bool {
            return !unicode.IsLetter(c) && !unicode.IsNumber(c)
        }
        fmt.Printf("Fields are: %q", strings.FieldsFunc("  foo1;bar2,baz3...", f))
        

        Output:

        Fields are: ["foo1" "bar2" "baz3"]
        

        func HasPrefix

        func HasPrefix(s, prefix string) bool

        HasPrefix reports whether the string s begins with prefix.

        Example

        Code:

        fmt.Println(strings.HasPrefix("Gopher", "Go"))
        fmt.Println(strings.HasPrefix("Gopher", "C"))
        fmt.Println(strings.HasPrefix("Gopher", ""))
        

        Output:

        true
        false
        true
        

        func HasSuffix

        func HasSuffix(s, suffix string) bool

        HasSuffix reports whether the string s ends with suffix.

        Example

        Code:

        fmt.Println(strings.HasSuffix("Amigo", "go"))
        fmt.Println(strings.HasSuffix("Amigo", "O"))
        fmt.Println(strings.HasSuffix("Amigo", "Ami"))
        fmt.Println(strings.HasSuffix("Amigo", ""))
        

        Output:

        true
        false
        false
        true
        

        func Index

        func Index(s, substr string) int

        Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.

        Example

        Code:

        fmt.Println(strings.Index("chicken", "ken"))
        fmt.Println(strings.Index("chicken", "dmr"))
        

        Output:

        4
        -1
        

        func IndexAny

        func IndexAny(s, chars string) int

        IndexAny returns the index of the first instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.

        Example

        Code:

        fmt.Println(strings.IndexAny("chicken", "aeiouy"))
        fmt.Println(strings.IndexAny("crwth", "aeiouy"))
        

        Output:

        2
        -1
        

        func IndexByte

        func IndexByte(s string, c byte) int

        IndexByte returns the index of the first instance of c in s, or -1 if c is not present in s.

        Example

        Code:

        fmt.Println(strings.IndexByte("golang", 'g'))
        fmt.Println(strings.IndexByte("gophers", 'h'))
        fmt.Println(strings.IndexByte("golang", 'x'))
        

        Output:

        0
        3
        -1
        

        func IndexFunc

        func IndexFunc(s string, f func(rune) bool) int

        IndexFunc returns the index into s of the first Unicode code point satisfying f(c), or -1 if none do.

        Example

        Code:

        f := func(c rune) bool {
            return unicode.Is(unicode.Han, c)
        }
        fmt.Println(strings.IndexFunc("Hello, 世界", f))
        fmt.Println(strings.IndexFunc("Hello, world", f))
        

        Output:

        7
        -1
        

        func IndexRune

        func IndexRune(s string, r rune) int

        IndexRune returns the index of the first instance of the Unicode code point r, or -1 if rune is not present in s. If r is utf8.RuneError, it returns the first instance of any invalid UTF-8 byte sequence.

        Example

        Code:

        fmt.Println(strings.IndexRune("chicken", 'k'))
        fmt.Println(strings.IndexRune("chicken", 'd'))
        

        Output:

        4
        -1
        

        func Join

        func Join(elems []string, sep string) string

        Join concatenates the elements of its first argument to create a single string. The separator string sep is placed between elements in the resulting string.

        Example

        Code:

        s := []string{"foo", "bar", "baz"}
        fmt.Println(strings.Join(s, ", "))
        

        Output:

        foo, bar, baz
        

        func LastIndex

        func LastIndex(s, substr string) int

        LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present in s.

        Example

        Code:

        fmt.Println(strings.Index("go gopher", "go"))
        fmt.Println(strings.LastIndex("go gopher", "go"))
        fmt.Println(strings.LastIndex("go gopher", "rodent"))
        

        Output:

        0
        3
        -1
        

        func LastIndexAny

        func LastIndexAny(s, chars string) int

        LastIndexAny returns the index of the last instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.

        Example

        Code:

        fmt.Println(strings.LastIndexAny("go gopher", "go"))
        fmt.Println(strings.LastIndexAny("go gopher", "rodent"))
        fmt.Println(strings.LastIndexAny("go gopher", "fail"))
        

        Output:

        4
        8
        -1
        

        func LastIndexByte

        func LastIndexByte(s string, c byte) int

        LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s.

        Example

        Code:

        fmt.Println(strings.LastIndexByte("Hello, world", 'l'))
        fmt.Println(strings.LastIndexByte("Hello, world", 'o'))
        fmt.Println(strings.LastIndexByte("Hello, world", 'x'))
        

        Output:

        10
        8
        -1
        

        func LastIndexFunc

        func LastIndexFunc(s string, f func(rune) bool) int

        LastIndexFunc returns the index into s of the last Unicode code point satisfying f(c), or -1 if none do.

        Example

        Code:

        fmt.Println(strings.LastIndexFunc("go 123", unicode.IsNumber))
        fmt.Println(strings.LastIndexFunc("123 go", unicode.IsNumber))
        fmt.Println(strings.LastIndexFunc("go", unicode.IsNumber))
        

        Output:

        5
        2
        -1
        

        func Map

        func Map(mapping func(rune) rune, s string) string

        Map returns a copy of the string s with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement.

        Example

        Code:

        rot13 := func(r rune) rune {
            switch {
            case r >= 'A' && r <= 'Z':
                return 'A' + (r-'A'+13)%26
            case r >= 'a' && r <= 'z':
                return 'a' + (r-'a'+13)%26
            }
            return r
        }
        fmt.Println(strings.Map(rot13, "'Twas brillig and the slithy gopher..."))
        

        Output:

        'Gjnf oevyyvt naq gur fyvgul tbcure...
        

        func Repeat

        func Repeat(s string, count int) string

        Repeat returns a new string consisting of count copies of the string s.

        It panics if count is negative or if the result of (len(s) * count) overflows.

        Example

        Code:

        fmt.Println("ba" + strings.Repeat("na", 2))
        

        Output:

        banana
        

        func Replace

        func Replace(s, old, new string, n int) string

        Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.

        Example

        Code:

        fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))
        fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))
        

        Output:

        oinky oinky oink
        moo moo moo
        

        func ReplaceAll

        func ReplaceAll(s, old, new string) string

        ReplaceAll returns a copy of the string s with all non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string.

        Example

        Code:

        fmt.Println(strings.ReplaceAll("oink oink oink", "oink", "moo"))
        

        Output:

        moo moo moo
        

        func Split

        func Split(s, sep string) []string

        Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.

        If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s.

        If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice.

        It is equivalent to SplitN with a count of -1.

        To split around the first instance of a separator, see Cut.

        Example

        Code:

        fmt.Printf("%q\n", strings.Split("a,b,c", ","))
        fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
        fmt.Printf("%q\n", strings.Split(" xyz ", ""))
        fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))
        

        Output:

        ["a" "b" "c"]
        ["" "man " "plan " "canal panama"]
        [" " "x" "y" "z" " "]
        [""]
        

        func SplitAfter

        func SplitAfter(s, sep string) []string

        SplitAfter slices s into all substrings after each instance of sep and returns a slice of those substrings.

        If s does not contain sep and sep is not empty, SplitAfter returns a slice of length 1 whose only element is s.

        If sep is empty, SplitAfter splits after each UTF-8 sequence. If both s and sep are empty, SplitAfter returns an empty slice.

        It is equivalent to SplitAfterN with a count of -1.

        Example

        Code:

        fmt.Printf("%q\n", strings.SplitAfter("a,b,c", ","))
        

        Output:

        ["a," "b," "c"]
        

        func SplitAfterN

        func SplitAfterN(s, sep string, n int) []string

        SplitAfterN slices s into substrings after each instance of sep and returns a slice of those substrings.

        The count determines the number of substrings to return:

        n > 0: at most n substrings; the last substring will be the unsplit remainder.
        n == 0: the result is nil (zero substrings)
        n < 0: all substrings
        

        Edge cases for s and sep (for example, empty strings) are handled as described in the documentation for SplitAfter.

        Example

        Code:

        fmt.Printf("%q\n", strings.SplitAfterN("a,b,c", ",", 2))
        

        Output:

        ["a," "b,c"]
        

        func SplitN

        func SplitN(s, sep string, n int) []string

        SplitN slices s into substrings separated by sep and returns a slice of the substrings between those separators.

        The count determines the number of substrings to return:

        n > 0: at most n substrings; the last substring will be the unsplit remainder.
        n == 0: the result is nil (zero substrings)
        n < 0: all substrings
        

        Edge cases for s and sep (for example, empty strings) are handled as described in the documentation for Split.

        To split around the first instance of a separator, see Cut.

        Example

        Code:

        fmt.Printf("%q\n", strings.SplitN("a,b,c", ",", 2))
        z := strings.SplitN("a,b,c", ",", 0)
        fmt.Printf("%q (nil = %v)\n", z, z == nil)
        

        Output:

        ["a" "b,c"]
        [] (nil = true)
        

        func Title

        func Title(s string) string

        Title returns a copy of the string s with all Unicode letters that begin words mapped to their Unicode title case.

        Deprecated: The rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.

        Example

        Code:

        // Compare this example to the ToTitle example.
        fmt.Println(strings.Title("her royal highness"))
        fmt.Println(strings.Title("loud noises"))
        fmt.Println(strings.Title("хлеб"))
        

        Output:

        Her Royal Highness
        Loud Noises
        Хлеб
        

        func ToLower

        func ToLower(s string) string

        ToLower returns s with all Unicode letters mapped to their lower case.

        Example

        Code:

        fmt.Println(strings.ToLower("Gopher"))
        

        Output:

        gopher
        

        func ToLowerSpecial

        func ToLowerSpecial(c unicode.SpecialCase, s string) string

        ToLowerSpecial returns a copy of the string s with all Unicode letters mapped to their lower case using the case mapping specified by c.

        Example

        Code:

        fmt.Println(strings.ToLowerSpecial(unicode.TurkishCase, "Önnek İş"))
        

        Output:

        önnek iş
        

        func ToTitle

        func ToTitle(s string) string

        ToTitle returns a copy of the string s with all Unicode letters mapped to their Unicode title case.

        Example

        Code:

        // Compare this example to the Title example.
        fmt.Println(strings.ToTitle("her royal highness"))
        fmt.Println(strings.ToTitle("loud noises"))
        fmt.Println(strings.ToTitle("хлеб"))
        

        Output:

        HER ROYAL HIGHNESS
        LOUD NOISES
        ХЛЕБ
        

        func ToTitleSpecial

        func ToTitleSpecial(c unicode.SpecialCase, s string) string

        ToTitleSpecial returns a copy of the string s with all Unicode letters mapped to their Unicode title case, giving priority to the special casing rules.

        Example

        Code:

        fmt.Println(strings.ToTitleSpecial(unicode.TurkishCase, "dünyanın ilk borsa yapısı Aizonai kabul edilir"))
        

        Output:

        DÜNYANIN İLK BORSA YAPISI AİZONAİ KABUL EDİLİR
        

        func ToUpper

        func ToUpper(s string) string

        ToUpper returns s with all Unicode letters mapped to their upper case.

        Example

        Code:

        fmt.Println(strings.ToUpper("Gopher"))
        

        Output:

        GOPHER
        

        func ToUpperSpecial

        func ToUpperSpecial(c unicode.SpecialCase, s string) string

        ToUpperSpecial returns a copy of the string s with all Unicode letters mapped to their upper case using the case mapping specified by c.

        Example

        Code:

        fmt.Println(strings.ToUpperSpecial(unicode.TurkishCase, "örnek iş"))
        

        Output:

        ÖRNEK İŞ
        

        func ToValidUTF8

        func ToValidUTF8(s, replacement string) string

        ToValidUTF8 returns a copy of the string s with each run of invalid UTF-8 byte sequences replaced by the replacement string, which may be empty.

        Example

        Code:

        fmt.Printf("%s\n", strings.ToValidUTF8("abc", "\uFFFD"))
        fmt.Printf("%s\n", strings.ToValidUTF8("a\xffb\xC0\xAFc\xff", ""))
        fmt.Printf("%s\n", strings.ToValidUTF8("\xed\xa0\x80", "abc"))
        

        Output:

        abc
        abc
        abc
        

        func Trim

        func Trim(s, cutset string) string

        Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.

        Example

        Code:

        fmt.Print(strings.Trim("¡¡¡Hello, Gophers!!!", "!¡"))
        

        Output:

        Hello, Gophers
        

        func TrimFunc

        func TrimFunc(s string, f func(rune) bool) string

        TrimFunc returns a slice of the string s with all leading and trailing Unicode code points c satisfying f(c) removed.

        Example

        Code:

        fmt.Print(strings.TrimFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
            return !unicode.IsLetter(r) && !unicode.IsNumber(r)
        }))
        

        Output:

        Hello, Gophers
        

        func TrimLeft

        func TrimLeft(s, cutset string) string

        TrimLeft returns a slice of the string s with all leading Unicode code points contained in cutset removed.

        To remove a prefix, use TrimPrefix instead.

        Example

        Code:

        fmt.Print(strings.TrimLeft("¡¡¡Hello, Gophers!!!", "!¡"))
        

        Output:

        Hello, Gophers!!!
        

        func TrimLeftFunc

        func TrimLeftFunc(s string, f func(rune) bool) string

        TrimLeftFunc returns a slice of the string s with all leading Unicode code points c satisfying f(c) removed.

        Example

        Code:

        fmt.Print(strings.TrimLeftFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
            return !unicode.IsLetter(r) && !unicode.IsNumber(r)
        }))
        

        Output:

        Hello, Gophers!!!
        

        func TrimPrefix

        func TrimPrefix(s, prefix string) string

        TrimPrefix returns s without the provided leading prefix string. If s doesn't start with prefix, s is returned unchanged.

        Example

        Code:

        var s = "¡¡¡Hello, Gophers!!!"
        s = strings.TrimPrefix(s, "¡¡¡Hello, ")
        s = strings.TrimPrefix(s, "¡¡¡Howdy, ")
        fmt.Print(s)
        

        Output:

        Gophers!!!
        

        func TrimRight

        func TrimRight(s, cutset string) string

        TrimRight returns a slice of the string s, with all trailing Unicode code points contained in cutset removed.

        To remove a suffix, use TrimSuffix instead.

        Example

        Code:

        fmt.Print(strings.TrimRight("¡¡¡Hello, Gophers!!!", "!¡"))
        

        Output:

        ¡¡¡Hello, Gophers
        

        func TrimRightFunc

        func TrimRightFunc(s string, f func(rune) bool) string

        TrimRightFunc returns a slice of the string s with all trailing Unicode code points c satisfying f(c) removed.

        Example

        Code:

        fmt.Print(strings.TrimRightFunc("¡¡¡Hello, Gophers!!!", func(r rune) bool {
            return !unicode.IsLetter(r) && !unicode.IsNumber(r)
        }))
        

        Output:

        ¡¡¡Hello, Gophers
        

        func TrimSpace

        func TrimSpace(s string) string

        TrimSpace returns a slice of the string s, with all leading and trailing white space removed, as defined by Unicode.

        Example

        Code:

        fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
        

        Output:

        Hello, Gophers
        

        func TrimSuffix

        func TrimSuffix(s, suffix string) string

        TrimSuffix returns s without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.

        Example

        Code:

        var s = "¡¡¡Hello, Gophers!!!"
        s = strings.TrimSuffix(s, ", Gophers!!!")
        s = strings.TrimSuffix(s, ", Marmots!!!")
        fmt.Print(s)
        

        Output:

        ¡¡¡Hello
        

        type Builder

        A Builder is used to efficiently build a string using Builder.Write methods. It minimizes memory copying. The zero value is ready to use. Do not copy a non-zero Builder.

        type Builder struct {
            // contains filtered or unexported fields
        }
        

        Example

        Code:

        var b strings.Builder
        for i := 3; i >= 1; i-- {
            fmt.Fprintf(&b, "%d...", i)
        }
        b.WriteString("ignition")
        fmt.Println(b.String())
        
        

        Output:

        3...2...1...ignition
        

        func (*Builder) Cap

        func (b *Builder) Cap() int

        Cap returns the capacity of the builder's underlying byte slice. It is the total space allocated for the string being built and includes any bytes already written.

        func (*Builder) Grow

        func (b *Builder) Grow(n int)

        Grow grows b's capacity, if necessary, to guarantee space for another n bytes. After Grow(n), at least n bytes can be written to b without another allocation. If n is negative, Grow panics.

        func (*Builder) Len

        func (b *Builder) Len() int

        Len returns the number of accumulated bytes; b.Len() == len(b.String()).

        func (*Builder) Reset

        func (b *Builder) Reset()

        Reset resets the Builder to be empty.

        func (*Builder) String

        func (b *Builder) String() string

        String returns the accumulated string.

        func (*Builder) Write

        func (b *Builder) Write(p []byte) (int, error)

        Write appends the contents of p to b's buffer. Write always returns len(p), nil.

        func (*Builder) WriteByte

        func (b *Builder) WriteByte(c byte) error

        WriteByte appends the byte c to b's buffer. The returned error is always nil.

        func (*Builder) WriteRune

        func (b *Builder) WriteRune(r rune) (int, error)

        WriteRune appends the UTF-8 encoding of Unicode code point r to b's buffer. It returns the length of r and a nil error.

        func (*Builder) WriteString

        func (b *Builder) WriteString(s string) (int, error)

        WriteString appends the contents of s to b's buffer. It returns the length of s and a nil error.

        type Reader

        A Reader implements the io.Reader, io.ReaderAt, io.ByteReader, io.ByteScanner, io.RuneReader, io.RuneScanner, io.Seeker, and io.WriterTo interfaces by reading from a string. The zero value for Reader operates like a Reader of an empty string.

        type Reader struct {
            // contains filtered or unexported fields
        }
        

        func NewReader

        func NewReader(s string) *Reader

        NewReader returns a new Reader reading from s. It is similar to bytes.NewBufferString but more efficient and non-writable.

        func (*Reader) Len

        func (r *Reader) Len() int

        Len returns the number of bytes of the unread portion of the string.

        func (*Reader) Read

        func (r *Reader) Read(b []byte) (n int, err error)

        Read implements the io.Reader interface.

        func (*Reader) ReadAt

        func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)

        ReadAt implements the io.ReaderAt interface.

        func (*Reader) ReadByte

        func (r *Reader) ReadByte() (byte, error)

        ReadByte implements the io.ByteReader interface.

        func (*Reader) ReadRune

        func (r *Reader) ReadRune() (ch rune, size int, err error)

        ReadRune implements the io.RuneReader interface.

        func (*Reader) Reset

        func (r *Reader) Reset(s string)

        Reset resets the Reader to be reading from s.

        func (*Reader) Seek

        func (r *Reader) Seek(offset int64, whence int) (int64, error)

        Seek implements the io.Seeker interface.

        func (*Reader) Size

        func (r *Reader) Size() int64

        Size returns the original length of the underlying string. Size is the number of bytes available for reading via Reader.ReadAt. The returned value is always the same and is not affected by calls to any other method.

        func (*Reader) UnreadByte

        func (r *Reader) UnreadByte() error

        UnreadByte implements the io.ByteScanner interface.

        func (*Reader) UnreadRune

        func (r *Reader) UnreadRune() error

        UnreadRune implements the io.RuneScanner interface.

        func (*Reader) WriteTo

        func (r *Reader) WriteTo(w io.Writer) (n int64, err error)

        WriteTo implements the io.WriterTo interface.

        type Replacer

        Replacer replaces a list of strings with replacements. It is safe for concurrent use by multiple goroutines.

        type Replacer struct {
            // contains filtered or unexported fields
        }
        

        func NewReplacer

        func NewReplacer(oldnew ...string) *Replacer

        NewReplacer returns a new Replacer from a list of old, new string pairs. Replacements are performed in the order they appear in the target string, without overlapping matches. The old string comparisons are done in argument order.

        NewReplacer panics if given an odd number of arguments.

        Example

        Code:

        r := strings.NewReplacer("<", "&lt;", ">", "&gt;")
        fmt.Println(r.Replace("This is <b>HTML</b>!"))
        

        Output:

        This is &lt;b&gt;HTML&lt;/b&gt;!
        

        func (*Replacer) Replace

        func (r *Replacer) Replace(s string) string

        Replace returns a copy of s with all replacements performed.

        func (*Replacer) WriteString

        func (r *Replacer) WriteString(w io.Writer, s string) (n int, err error)

        WriteString writes s to w with all replacements performed.